file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
NegatedNumberCondition.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/condition/NegatedNumberCondition.java
package org.chronos.chronodb.internal.impl.query.condition; import org.chronos.chronodb.api.query.NumberCondition; public interface NegatedNumberCondition extends NumberCondition, NegatedCondition { @Override default boolean applies(final long value, final long searchValue) { return this.negate().applies(value, searchValue) == false; } @Override public default boolean applies(final double value, final double searchValue, final double equalityTolerance) { return this.negate().applies(value, searchValue, equalityTolerance) == false; } }
556
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EqualsCondition.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/condition/EqualsCondition.java
package org.chronos.chronodb.internal.impl.query.condition; import static com.google.common.base.Preconditions.*; import org.chronos.chronodb.api.query.NumberCondition; import org.chronos.chronodb.api.query.StringCondition; import org.chronos.chronodb.internal.impl.query.TextMatchMode; import org.chronos.common.exceptions.UnknownEnumLiteralException; public class EqualsCondition extends AbstractCondition implements StringCondition, NumberCondition { public static final EqualsCondition INSTANCE = new EqualsCondition(); protected EqualsCondition() { super("=="); } @Override public NotEqualsCondition negate() { return NotEqualsCondition.INSTANCE; } @Override public boolean applies(final String text, final String searchValue, final TextMatchMode matchMode) { switch (matchMode) { case CASE_INSENSITIVE: return text.toLowerCase().equals(searchValue.toLowerCase()); case STRICT: return text.equals(searchValue); default: throw new UnknownEnumLiteralException(matchMode); } } @Override public boolean applies(final long value, final long searchValue) { return value == searchValue; } @Override public boolean applies(final double value, final double searchValue, final double equalityTolerance) { checkArgument(equalityTolerance >= 0, "Precondition violation: argument 'equalityTolerance' must not be negative!"); double low = value - equalityTolerance; double high = value + equalityTolerance; if (low <= searchValue && searchValue <= high) { return true; } else { return false; } } @Override public String toString() { return "Equals"; } }
1,618
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AbstractCondition.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/condition/AbstractCondition.java
package org.chronos.chronodb.internal.impl.query.condition; import static com.google.common.base.Preconditions.*; import org.chronos.chronodb.api.query.Condition; public abstract class AbstractCondition implements Condition { // ================================================================================================================= // FIELDS // ================================================================================================================= /** The in-fix representation for this literal. */ private String infix; // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= /** * Constructs a new condition, for internal use only. * * @param infixRepresentation * The in-fix representation of the condition. Must not be <code>null</code>. */ protected AbstractCondition(final String infixRepresentation) { checkNotNull(infixRepresentation, "Precondition violation - argument 'infixRepresentation' must not be NULL!"); this.infix = infixRepresentation; } @Override public String getInfix() { return this.infix; } }
1,282
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
NotMatchesRegexCondition.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/condition/string/NotMatchesRegexCondition.java
package org.chronos.chronodb.internal.impl.query.condition.string; import org.chronos.chronodb.api.query.StringCondition; import org.chronos.chronodb.internal.impl.query.condition.AbstractCondition; import org.chronos.chronodb.internal.impl.query.condition.NegatedStringCondition; public class NotMatchesRegexCondition extends AbstractCondition implements NegatedStringCondition { // ================================================================================================================= // CONSTANTS // ================================================================================================================= public static final NotMatchesRegexCondition INSTANCE = new NotMatchesRegexCondition(); // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= protected NotMatchesRegexCondition() { super("!matches"); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public boolean acceptsEmptyValue() { return true; } @Override public StringCondition negate() { return MatchesRegexCondition.INSTANCE; } @Override public String toString() { return "NotMatchesRegex"; } }
1,526
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
NotEndsWithCondition.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/condition/string/NotEndsWithCondition.java
package org.chronos.chronodb.internal.impl.query.condition.string; import org.chronos.chronodb.internal.impl.query.condition.AbstractCondition; import org.chronos.chronodb.internal.impl.query.condition.NegatedStringCondition; public class NotEndsWithCondition extends AbstractCondition implements NegatedStringCondition { // ================================================================================================================= // CONSTANTS // ================================================================================================================= public static final NotEndsWithCondition INSTANCE = new NotEndsWithCondition(); // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= protected NotEndsWithCondition() { super("!-|"); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public boolean acceptsEmptyValue() { return true; } @Override public EndsWithCondition negate() { return EndsWithCondition.INSTANCE; } @Override public String toString() { return "NotEndsWith"; } }
1,445
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
MatchesRegexCondition.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/condition/string/MatchesRegexCondition.java
package org.chronos.chronodb.internal.impl.query.condition.string; import java.util.regex.Pattern; import org.chronos.chronodb.api.query.StringCondition; import org.chronos.chronodb.internal.impl.query.TextMatchMode; import org.chronos.chronodb.internal.impl.query.condition.AbstractCondition; import org.chronos.common.exceptions.UnknownEnumLiteralException; public class MatchesRegexCondition extends AbstractCondition implements StringCondition { // ================================================================================================================= // CONSTANTS // ================================================================================================================= public static final MatchesRegexCondition INSTANCE = new MatchesRegexCondition(); // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= protected MatchesRegexCondition() { super("matches"); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public StringCondition negate() { return NotMatchesRegexCondition.INSTANCE; } @Override public boolean applies(final String text, final String searchValue, final TextMatchMode matchMode) { switch (matchMode) { case CASE_INSENSITIVE: return Pattern.matches("(?i)" + searchValue, text); case STRICT: return Pattern.matches(searchValue, text); default: throw new UnknownEnumLiteralException(matchMode); } } @Override public String toString() { return "MatchesRegex"; } }
1,867
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
NotContainsCondition.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/condition/string/NotContainsCondition.java
package org.chronos.chronodb.internal.impl.query.condition.string; import org.chronos.chronodb.api.query.StringCondition; import org.chronos.chronodb.internal.impl.query.condition.AbstractCondition; import org.chronos.chronodb.internal.impl.query.condition.NegatedStringCondition; public class NotContainsCondition extends AbstractCondition implements NegatedStringCondition { // ================================================================================================================= // CONSTANTS // ================================================================================================================= public static final NotContainsCondition INSTANCE = new NotContainsCondition(); // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= protected NotContainsCondition() { super("!contains"); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public boolean acceptsEmptyValue() { return true; } @Override public StringCondition negate() { return ContainsCondition.INSTANCE; } @Override public String toString() { return "NotContains"; } }
1,504
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
StartsWithCondition.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/condition/string/StartsWithCondition.java
package org.chronos.chronodb.internal.impl.query.condition.string; import org.chronos.chronodb.api.query.StringCondition; import org.chronos.chronodb.internal.impl.query.TextMatchMode; import org.chronos.chronodb.internal.impl.query.condition.AbstractCondition; import org.chronos.common.exceptions.UnknownEnumLiteralException; public class StartsWithCondition extends AbstractCondition implements StringCondition { // ================================================================================================================= // CONSTANTS // ================================================================================================================= public static final StartsWithCondition INSTANCE = new StartsWithCondition(); // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= protected StartsWithCondition() { super("|-"); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public StringCondition negate() { return NotStartsWithCondition.INSTANCE; } @Override public boolean applies(final String text, final String searchValue, final TextMatchMode matchMode) { switch (matchMode) { case CASE_INSENSITIVE: return text.toLowerCase().startsWith(searchValue.toLowerCase()); case STRICT: return text.startsWith(searchValue); default: throw new UnknownEnumLiteralException(matchMode); } } @Override public String toString() { return "StartsWith"; } }
1,824
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
NotStartsWithCondition.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/condition/string/NotStartsWithCondition.java
package org.chronos.chronodb.internal.impl.query.condition.string; import org.chronos.chronodb.api.query.StringCondition; import org.chronos.chronodb.internal.impl.query.condition.AbstractCondition; import org.chronos.chronodb.internal.impl.query.condition.NegatedStringCondition; public class NotStartsWithCondition extends AbstractCondition implements NegatedStringCondition { // ================================================================================================================= // CONSTANTS // ================================================================================================================= public static final NotStartsWithCondition INSTANCE = new NotStartsWithCondition(); // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= protected NotStartsWithCondition() { super("!|-"); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public boolean acceptsEmptyValue() { return true; } @Override public StringCondition negate() { return StartsWithCondition.INSTANCE; } @Override public String toString() { return "NotStartsWith"; } }
1,509
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ContainsCondition.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/condition/string/ContainsCondition.java
package org.chronos.chronodb.internal.impl.query.condition.string; import org.chronos.chronodb.api.query.StringCondition; import org.chronos.chronodb.internal.impl.query.TextMatchMode; import org.chronos.chronodb.internal.impl.query.condition.AbstractCondition; import org.chronos.common.exceptions.UnknownEnumLiteralException; public class ContainsCondition extends AbstractCondition implements StringCondition { // ================================================================================================================= // CONSTANTS // ================================================================================================================= public static final ContainsCondition INSTANCE = new ContainsCondition(); // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= protected ContainsCondition() { super("contains"); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public StringCondition negate() { return NotContainsCondition.INSTANCE; } @Override public boolean applies(final String text, final String searchValue, final TextMatchMode matchMode) { switch (matchMode) { case CASE_INSENSITIVE: return text.toLowerCase().contains(searchValue.toLowerCase()); case STRICT: return text.contains(searchValue); default: throw new UnknownEnumLiteralException(matchMode); } } @Override public String toString() { return "Contains"; } }
1,815
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EndsWithCondition.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/condition/string/EndsWithCondition.java
package org.chronos.chronodb.internal.impl.query.condition.string; import org.chronos.chronodb.api.query.StringCondition; import org.chronos.chronodb.internal.impl.query.TextMatchMode; import org.chronos.chronodb.internal.impl.query.condition.AbstractCondition; import org.chronos.common.exceptions.UnknownEnumLiteralException; public class EndsWithCondition extends AbstractCondition implements StringCondition { // ================================================================================================================= // CONSTANTS // ================================================================================================================= public static final EndsWithCondition INSTANCE = new EndsWithCondition(); // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= protected EndsWithCondition() { super("-|"); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public StringCondition negate() { return NotEndsWithCondition.INSTANCE; } @Override public boolean applies(final String text, final String searchValue, final TextMatchMode matchMode) { switch (matchMode) { case CASE_INSENSITIVE: return text.toLowerCase().endsWith(searchValue.toLowerCase()); case STRICT: return text.endsWith(searchValue); default: throw new UnknownEnumLiteralException(matchMode); } } @Override public String toString() { return "EndsWith"; } }
1,809
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
LessThanCondition.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/condition/number/LessThanCondition.java
package org.chronos.chronodb.internal.impl.query.condition.number; import org.chronos.chronodb.api.query.NumberCondition; import org.chronos.chronodb.internal.impl.query.condition.AbstractCondition; import org.chronos.chronodb.internal.impl.query.condition.NegatedNumberCondition; public class LessThanCondition extends AbstractCondition implements NegatedNumberCondition { // ================================================================================================================= // CONSTANTS // ================================================================================================================= public static final LessThanCondition INSTANCE = new LessThanCondition(); // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= protected LessThanCondition() { super("<"); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public NumberCondition negate() { return GreaterThanOrEqualToCondition.INSTANCE; } @Override public String toString() { return "LessThan"; } }
1,424
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
GreaterThanOrEqualToCondition.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/condition/number/GreaterThanOrEqualToCondition.java
package org.chronos.chronodb.internal.impl.query.condition.number; import static com.google.common.base.Preconditions.*; import org.chronos.chronodb.api.query.NumberCondition; import org.chronos.chronodb.internal.impl.query.condition.AbstractCondition; public class GreaterThanOrEqualToCondition extends AbstractCondition implements NumberCondition { // ================================================================================================================= // CONSTANTS // ================================================================================================================= public static final GreaterThanOrEqualToCondition INSTANCE = new GreaterThanOrEqualToCondition(); // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= protected GreaterThanOrEqualToCondition() { super(">="); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public NumberCondition negate() { return LessThanCondition.INSTANCE; } @Override public boolean applies(final long value, final long searchValue) { return value >= searchValue; } @Override public boolean applies(final double value, final double searchValue, final double equalityTolerance) { checkArgument(equalityTolerance >= 0, "Precondition violation: argument 'equalityTolerance' must not be negative!"); return value >= searchValue; } @Override public String toString() { return "GreaterThanOrEqualTo"; } }
1,822
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
LessThanOrEqualToCondition.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/condition/number/LessThanOrEqualToCondition.java
package org.chronos.chronodb.internal.impl.query.condition.number; import org.chronos.chronodb.api.query.NumberCondition; import org.chronos.chronodb.internal.impl.query.condition.AbstractCondition; import org.chronos.chronodb.internal.impl.query.condition.NegatedNumberCondition; public class LessThanOrEqualToCondition extends AbstractCondition implements NegatedNumberCondition { // ================================================================================================================= // CONSTANTS // ================================================================================================================= public static final LessThanOrEqualToCondition INSTANCE = new LessThanOrEqualToCondition(); // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= protected LessThanOrEqualToCondition() { super("<="); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public NumberCondition negate() { return GreaterThanCondition.INSTANCE; } @Override public String toString() { return "LessThanOrEqualTo"; } }
1,461
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
GreaterThanCondition.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/condition/number/GreaterThanCondition.java
package org.chronos.chronodb.internal.impl.query.condition.number; import static com.google.common.base.Preconditions.*; import org.chronos.chronodb.api.query.NumberCondition; import org.chronos.chronodb.internal.impl.query.condition.AbstractCondition; public class GreaterThanCondition extends AbstractCondition implements NumberCondition { // ================================================================================================================= // CONSTANTS // ================================================================================================================= public static final GreaterThanCondition INSTANCE = new GreaterThanCondition(); // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= protected GreaterThanCondition() { super(">"); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public NumberCondition negate() { return LessThanOrEqualToCondition.INSTANCE; } @Override public boolean applies(final long value, final long searchValue) { return value > searchValue; } @Override public boolean applies(final double value, final double searchValue, final double equalityTolerance) { checkArgument(equalityTolerance >= 0, "Precondition violation: argument 'equalityTolerance' must not be negative!"); return value > searchValue; } @Override public String toString() { return "GreaterThan"; } }
1,784
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
SetWithoutStringCondition.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/condition/containment/SetWithoutStringCondition.java
package org.chronos.chronodb.internal.impl.query.condition.containment; import org.chronos.chronodb.api.query.StringContainmentCondition; import org.chronos.chronodb.internal.impl.query.TextMatchMode; import org.chronos.chronodb.internal.impl.query.condition.AbstractCondition; import java.util.Set; public class SetWithoutStringCondition extends AbstractCondition implements StringContainmentCondition { public static final SetWithoutStringCondition INSTANCE = new SetWithoutStringCondition(); protected SetWithoutStringCondition() { super("string without"); } @Override public StringWithinSetCondition negate() { return StringWithinSetCondition.INSTANCE; } @Override public boolean applies(final String elementToTest, final Set<String> collectionToTestAgainst, TextMatchMode matchMode) { if(collectionToTestAgainst == null || collectionToTestAgainst.isEmpty()){ return true; } return !StringWithinSetCondition.INSTANCE.applies(elementToTest, collectionToTestAgainst, matchMode); } @Override public boolean isNegated() { return true; } @Override public boolean acceptsEmptyValue() { return true; } @Override public String toString() { return "String Without"; } }
1,323
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
StringWithinSetCondition.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/condition/containment/StringWithinSetCondition.java
package org.chronos.chronodb.internal.impl.query.condition.containment; import org.chronos.chronodb.api.query.StringContainmentCondition; import org.chronos.chronodb.internal.impl.query.TextMatchMode; import org.chronos.chronodb.internal.impl.query.condition.AbstractCondition; import org.chronos.common.exceptions.UnknownEnumLiteralException; import java.util.Set; public class StringWithinSetCondition extends AbstractCondition implements StringContainmentCondition { public static final StringWithinSetCondition INSTANCE = new StringWithinSetCondition(); protected StringWithinSetCondition() { super("string within"); } @Override public StringContainmentCondition negate() { return SetWithoutStringCondition.INSTANCE; } @Override public boolean applies(final String elementToTest, final Set<String> collectionToTestAgainst, final TextMatchMode matchMode) { if(collectionToTestAgainst == null || collectionToTestAgainst.isEmpty()){ return false; } switch(matchMode){ case STRICT: return collectionToTestAgainst.contains(elementToTest); case CASE_INSENSITIVE: for(String e : collectionToTestAgainst){ if(e == null){ if(elementToTest == null){ return true; }else{ continue; } } if(e.equalsIgnoreCase(elementToTest)){ return true; } } return false; default: throw new UnknownEnumLiteralException(matchMode); } } @Override public boolean isNegated() { return false; } @Override public boolean acceptsEmptyValue() { return false; } @Override public String toString() { return "String Within"; } }
1,992
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
SetWithoutLongCondition.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/condition/containment/SetWithoutLongCondition.java
package org.chronos.chronodb.internal.impl.query.condition.containment; import org.chronos.chronodb.api.query.ContainmentCondition; import org.chronos.chronodb.api.query.DoubleContainmentCondition; import org.chronos.chronodb.api.query.LongContainmentCondition; import org.chronos.chronodb.internal.impl.query.condition.AbstractCondition; import java.util.Set; public class SetWithoutLongCondition extends AbstractCondition implements LongContainmentCondition { public static final SetWithoutLongCondition INSTANCE = new SetWithoutLongCondition(); protected SetWithoutLongCondition() { super("long without"); } @Override public LongWithinSetCondition negate() { return LongWithinSetCondition.INSTANCE; } @Override public boolean applies(final long elementToTest, final Set<Long> collectionToTestAgainst) { if(collectionToTestAgainst == null || collectionToTestAgainst.isEmpty()){ return true; } return !LongWithinSetCondition.INSTANCE.applies(elementToTest, collectionToTestAgainst); } @Override public boolean isNegated() { return true; } @Override public boolean acceptsEmptyValue() { return true; } @Override public String toString() { return "Long Without"; } }
1,324
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
DoubleWithinSetCondition.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/condition/containment/DoubleWithinSetCondition.java
package org.chronos.chronodb.internal.impl.query.condition.containment; import org.chronos.chronodb.api.query.ContainmentCondition; import org.chronos.chronodb.api.query.DoubleContainmentCondition; import org.chronos.chronodb.api.query.StringContainmentCondition; import org.chronos.chronodb.internal.impl.query.TextMatchMode; import org.chronos.chronodb.internal.impl.query.condition.AbstractCondition; import org.chronos.common.exceptions.UnknownEnumLiteralException; import java.util.Set; public class DoubleWithinSetCondition extends AbstractCondition implements DoubleContainmentCondition { public static final DoubleWithinSetCondition INSTANCE = new DoubleWithinSetCondition(); protected DoubleWithinSetCondition() { super("double within"); } @Override public DoubleContainmentCondition negate() { return SetWithoutDoubleCondition.INSTANCE; } @Override public boolean applies(final double elementToTest, final Set<Double> collectionToTestAgainst, final double equalityTolerance) { if(collectionToTestAgainst == null || collectionToTestAgainst.isEmpty()){ return false; } double tolerance = Math.abs(equalityTolerance); for(Double e : collectionToTestAgainst){ if(e == null){ continue; } if(Math.abs(e - elementToTest) <= tolerance){ return true; } } return false; } @Override public boolean isNegated() { return false; } @Override public boolean acceptsEmptyValue() { return false; } @Override public String toString() { return "Double Within"; } }
1,717
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
SetWithoutDoubleCondition.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/condition/containment/SetWithoutDoubleCondition.java
package org.chronos.chronodb.internal.impl.query.condition.containment; import org.chronos.chronodb.api.query.DoubleContainmentCondition; import org.chronos.chronodb.api.query.StringContainmentCondition; import org.chronos.chronodb.internal.impl.query.TextMatchMode; import org.chronos.chronodb.internal.impl.query.condition.AbstractCondition; import java.util.Set; public class SetWithoutDoubleCondition extends AbstractCondition implements DoubleContainmentCondition { public static final SetWithoutDoubleCondition INSTANCE = new SetWithoutDoubleCondition(); protected SetWithoutDoubleCondition() { super("double without"); } @Override public DoubleWithinSetCondition negate() { return DoubleWithinSetCondition.INSTANCE; } @Override public boolean applies(final double elementToTest, final Set<Double> collectionToTestAgainst, double equalityTolerance) { if(collectionToTestAgainst == null || collectionToTestAgainst.isEmpty()){ return true; } return !DoubleWithinSetCondition.INSTANCE.applies(elementToTest, collectionToTestAgainst, equalityTolerance); } @Override public boolean isNegated() { return true; } @Override public boolean acceptsEmptyValue() { return true; } @Override public String toString() { return "Double Without"; } }
1,398
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
LongWithinSetCondition.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/condition/containment/LongWithinSetCondition.java
package org.chronos.chronodb.internal.impl.query.condition.containment; import org.chronos.chronodb.api.query.LongContainmentCondition; import org.chronos.chronodb.internal.impl.query.condition.AbstractCondition; import java.util.Set; public class LongWithinSetCondition extends AbstractCondition implements LongContainmentCondition { public static final LongWithinSetCondition INSTANCE = new LongWithinSetCondition(); protected LongWithinSetCondition() { super("long within"); } @Override public LongContainmentCondition negate() { return SetWithoutLongCondition.INSTANCE; } @Override public boolean applies(final long elementToTest, final Set<Long> collectionToTestAgainst) { if(collectionToTestAgainst == null || collectionToTestAgainst.isEmpty()){ return false; } return collectionToTestAgainst.contains(elementToTest); } @Override public boolean isNegated() { return false; } @Override public boolean acceptsEmptyValue() { return false; } @Override public String toString() { return "Long Within"; } }
1,165
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
StandardQueryOptimizer.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/optimizer/StandardQueryOptimizer.java
package org.chronos.chronodb.internal.impl.query.optimizer; import org.chronos.chronodb.api.query.ContainmentCondition; import org.chronos.chronodb.internal.api.query.ChronoDBQuery; import org.chronos.chronodb.internal.api.query.QueryOptimizer; import org.chronos.chronodb.internal.impl.query.parser.ast.*; import org.chronos.common.exceptions.UnknownEnumLiteralException; public class StandardQueryOptimizer implements QueryOptimizer { @Override public ChronoDBQuery optimize(final ChronoDBQuery query) { QueryElement ast = query.getRootElement(); ast = this.pushNegationInside(ast); ast = this.replaceRepeatedOrsWithContainment(ast); // return the optimized query return new ChronoDBQueryImpl(query.getKeyspace(), ast); } private QueryElement pushNegationInside(final QueryElement original) { if (original instanceof NotElement) { // case 1: our AST element is a negation; push it down QueryElement child = ((NotElement) original).getChild(); // drop the negation and return the negated child return this.getNegated(child); } else { // case 2: our AST element is not a negation; continue searching recursively if (original instanceof WhereElement) { // reached a where during scan without encountering a negation. Reuse it. return original; } else if (original instanceof BinaryOperatorElement) { // search recursively for negations in both child elements BinaryOperatorElement binaryOperatorElement = (BinaryOperatorElement) original; QueryElement left = this.pushNegationInside(binaryOperatorElement.getLeftChild()); QueryElement right = this.pushNegationInside(binaryOperatorElement.getRightChild()); // create a new binary element with the optimized children return new BinaryOperatorElement(left, binaryOperatorElement.getOperator(), right); } else { throw new IllegalArgumentException( "Encountered unknown subclass of QueryElement: '" + original.getClass().getName() + "'!"); } } } private QueryElement getNegated(final QueryElement original) { if (original instanceof WhereElement) { // negate the condition, eliminate the parent "not" return ((WhereElement<?, ?>) original).negate(); } else if (original instanceof NotElement) { // double negation elimination: use what's inside the inner "not" and discard both not operators QueryElement child = ((NotElement) original).getChild(); return this.pushNegationInside(child); } else if (original instanceof BinaryOperatorElement) { BinaryOperatorElement originalBinary = (BinaryOperatorElement) original; // invert the operator and push the negation into both children QueryElement negatedLeft = this.getNegated(originalBinary.getLeftChild()); QueryElement negatedRight = this.getNegated(originalBinary.getRightChild()); BinaryQueryOperator negatedOperator = null; switch (originalBinary.getOperator()) { case AND: negatedOperator = BinaryQueryOperator.OR; break; case OR: negatedOperator = BinaryQueryOperator.AND; break; default: throw new UnknownEnumLiteralException("Encountered unknown literal of BinaryOperatorElement: '" + originalBinary.getOperator() + "'!"); } return new BinaryOperatorElement(negatedLeft, negatedOperator, negatedRight); } else { throw new IllegalArgumentException( "Encountered unknown subclass of QueryElement: '" + original.getClass().getName() + "'!"); } } private QueryElement replaceRepeatedOrsWithContainment(final QueryElement original) { if (original instanceof WhereElement) { return original; } else if (original instanceof NotElement) { // this should not happen as we push negation inside... return original; } else if (original instanceof BinaryOperatorElement) { BinaryOperatorElement originalBinary = (BinaryOperatorElement) original; BinaryQueryOperator operator = originalBinary.getOperator(); QueryElement leftChild = replaceRepeatedOrsWithContainment(originalBinary.getLeftChild()); QueryElement rightChild = replaceRepeatedOrsWithContainment(originalBinary.getRightChild()); switch (operator) { case AND: return new BinaryOperatorElement(leftChild, operator, rightChild); case OR: if (leftChild instanceof WhereElement && rightChild instanceof WhereElement) { WhereElement<?, ?> leftWhere = (WhereElement<?, ?>) leftChild; WhereElement<?, ?> rightWhere = (WhereElement<?, ?>) rightChild; WhereElement<?, ? extends ContainmentCondition> inClause = leftWhere.collapseToInClause(rightWhere); if (inClause != null) { return inClause; } } return new BinaryOperatorElement(leftChild, operator, rightChild); default: throw new UnknownEnumLiteralException(operator); } }else { throw new IllegalArgumentException( "Encountered unknown subclass of QueryElement: '" + original.getClass().getName() + "'!"); } } }
5,827
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AbstractDatebackManager.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dateback/AbstractDatebackManager.java
package org.chronos.chronodb.internal.impl.dateback; import com.google.common.collect.Lists; import org.chronos.chronodb.api.Branch; import org.chronos.chronodb.api.Dateback; import org.chronos.chronodb.api.IndexManager; import org.chronos.chronodb.api.exceptions.ChronoDBBranchingException; import org.chronos.chronodb.internal.api.BranchInternal; import org.chronos.chronodb.internal.api.ChronoDBInternal; import org.chronos.chronodb.internal.api.DatebackManagerInternal; import org.chronos.chronodb.internal.api.dateback.log.DatebackOperation; import org.chronos.chronodb.internal.api.index.IndexManagerInternal; import org.chronos.common.autolock.AutoLock; import java.util.Comparator; import java.util.List; import java.util.function.Consumer; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.*; public abstract class AbstractDatebackManager implements DatebackManagerInternal { private final ChronoDBInternal db; private volatile Thread datebackThread; public AbstractDatebackManager(final ChronoDBInternal dbInstance) { checkNotNull(dbInstance, "Precondition violation - argument 'dbInstance' must not be NULL!"); this.db = dbInstance; } @Override public void dateback(final String branch, final Consumer<Dateback> function) { checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); boolean branchExists = this.db.getBranchManager().existsBranch(branch); if (branchExists == false) { throw new ChronoDBBranchingException("There is no Branch named '" + branch + "'!"); } checkNotNull(function, "Precondition violation - argument 'function' must not be NULL!"); try (AutoLock lock = this.db.lockExclusive()) { this.datebackThread = Thread.currentThread(); // create the dateback API try (DatebackImpl dateback = new DatebackImpl(this.db, branch, this::writeDatebackOperationToLog)) { // call the dateback function on the dateback object. It will // be closed automatically once the try-block ends, so it cannot // be "stolen" by user code. function.accept(dateback); } } finally { // clear the dateback thread this.datebackThread = null; // allow the storage backend to compact the storage (if necessary) this.compactStorage(branch); // clear all caches this.db.getCache().clear(); this.db.getIndexManager().clearQueryCache(); // mark all indices as dirty IndexManagerInternal indexManager = (IndexManagerInternal)this.db.getIndexManager(); indexManager.markAllIndicesAsDirty(); } } protected void compactStorage(String branch){ // override in subclasses if necessary } @Override public boolean isDatebackRunning() { return this.datebackThread != null; } @Override public void addDatebackOperationToLog(final DatebackOperation operation) { checkNotNull(operation, "Precondition violation - argument 'operation' must not be NULL!"); this.writeDatebackOperationToLog(operation); } protected ChronoDBInternal getOwningDb(){ return this.db; } protected abstract void writeDatebackOperationToLog(DatebackOperation operation); @Override public List<DatebackOperation> getDatebackOperationsPerformedBetween(String branch, long dateTimeMin, long dateTimeMax){ checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); checkArgument(dateTimeMin >= 0, "Precondition violation - argument 'dateTimeMin' must not be negative!"); checkArgument(dateTimeMax >= 0, "Precondition violation - argument 'dateTimeMax' must not be negative!"); checkArgument(dateTimeMin <= dateTimeMax, "Precondition violation - argument 'dateTimeMin' must be less than 'dateTimeMax'!"); BranchInternal b = this.getOwningDb().getBranchManager().getBranch(branch); if(b == null){ throw new IllegalArgumentException("The given branch name '" + branch + "' does not refer to any existing branch!"); } List<Branch> originsRecursive = b.getOriginsRecursive(); List<DatebackOperation> operations = Lists.newArrayList(); for(Branch localBranch : originsRecursive){ operations.addAll(this.getDatebackOperationsPerformedOnBranchBetween(localBranch.getName(), dateTimeMin, dateTimeMax)); } operations.addAll(this.getDatebackOperationsPerformedOnBranchBetween(branch, dateTimeMin, dateTimeMax)); operations.sort(Comparator.comparing(DatebackOperation::getBranch).thenComparing(DatebackOperation::getWallClockTime)); return operations; } protected abstract List<DatebackOperation> getDatebackOperationsPerformedOnBranchBetween(String branch, long dateTimeMin, long dateTimeMax); @Override public List<DatebackOperation> getDatebackOperationsAffectingTimestamp(String branch, long timestamp) { BranchInternal b = this.getOwningDb().getBranchManager().getBranch(branch); if(b == null){ throw new IllegalArgumentException("The given branch name '" + branch + "' does not refer to any existing branch!"); } List<Branch> branchList = Lists.newArrayList(b.getOriginsRecursive()); branchList.add(b); List<DatebackOperation> allOps = this.getAllPerformedDatebackOperations(); List<DatebackOperation> resultList = Lists.newArrayList(); for(int i = 0; i < branchList.size(); i++){ Branch currentBranch = branchList.get(i); long affectedTimestamp; if(i+1 < branchList.size()){ affectedTimestamp = branchList.get(i+1).getBranchingTimestamp(); }else{ // we are at the end of the parent-branch relationship. The timestamp we need to consider // here is our own parameter timestamp. affectedTimestamp = timestamp; } resultList.addAll(allOps.stream() .filter(op -> op.getBranch().equals(currentBranch.getName()) && op.affectsTimestamp(affectedTimestamp)) .collect(Collectors.toList()) ); } return resultList; } }
6,436
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
DatebackImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dateback/DatebackImpl.java
package org.chronos.chronodb.internal.impl.dateback; import com.google.common.collect.Sets; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.Dateback; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.api.key.TemporalKey; import org.chronos.chronodb.internal.api.BranchInternal; import org.chronos.chronodb.internal.api.ChronoDBInternal; import org.chronos.chronodb.internal.api.MutableTransactionConfiguration; import org.chronos.chronodb.internal.api.TemporalKeyValueStore; import org.chronos.chronodb.internal.api.dateback.log.DatebackLogger; import org.chronos.chronodb.internal.impl.DefaultTransactionConfiguration; import org.chronos.chronodb.internal.impl.dateback.log.*; import org.chronos.chronodb.internal.impl.dateback.log.v2.TransformCommitOperation2; import java.util.*; import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.Function; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.*; public class DatebackImpl implements Dateback, AutoCloseable { // ================================================================================================================= // FIELDS // ================================================================================================================= private final ChronoDBInternal db; private final String branch; private boolean closed; private final DatebackLogger logger; private long earliestTouchedTimestamp = Long.MAX_VALUE; // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= public DatebackImpl(final ChronoDBInternal dbInstance, final String branch, final DatebackLogger logger) { checkNotNull(dbInstance, "Precondition violation - argument 'dbInstance' must not be NULL!"); checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); checkNotNull(logger, "Precondition violation - argument 'logger' must not be NULL!"); this.db = dbInstance; this.logger = logger; this.branch = branch; this.closed = false; } // ================================================================================================================= // LIFECYCLE // ================================================================================================================= @Override public void close() { if (this.closed) { return; } this.cleanup(); this.closed = true; } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public boolean purgeEntry(final String keyspace, final String key, final long timestamp) { checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be neagtive!"); this.assertNotClosed(); boolean purged = this.getTKVS().datebackPurgeEntry(keyspace, key, timestamp); if (purged) { this.updateEarliestTouchedTimestamp(timestamp); this.logger.logDatebackOperation(new PurgeEntryOperation(this.branch, timestamp, keyspace, key)); } return purged; } @Override public void purgeKey(final String keyspace, final String key) { checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); this.assertNotClosed(); Collection<TemporalKey> changed = this.getTKVS().datebackPurgeKey(keyspace, key); if(changed.isEmpty()){ return; } this.updateEarliestTouchedTimestamp(changed); long minTimestamp = changed.stream().mapToLong(TemporalKey::getTimestamp).min().orElseThrow(IllegalStateException::new); long maxTimestamp = changed.stream().mapToLong(TemporalKey::getTimestamp).max().orElseThrow(IllegalStateException::new); this.logger.logDatebackOperation(new PurgeKeyOperation(this.branch, keyspace, key, minTimestamp, maxTimestamp)); } @Override public void purgeKey(final String keyspace, final String key, final BiPredicate<Long, Object> predicate) { checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); checkNotNull(predicate, "Precondition violation - argument 'predicate' must not be NULL!"); this.assertNotClosed(); Collection<TemporalKey> changed = this.getTKVS().datebackPurgeKey(keyspace, key, predicate); if(changed.isEmpty()){ return; } this.updateEarliestTouchedTimestamp(changed); long minTimestamp = changed.stream().mapToLong(TemporalKey::getTimestamp).min().orElseThrow(IllegalStateException::new); long maxTimestamp = changed.stream().mapToLong(TemporalKey::getTimestamp).max().orElseThrow(IllegalStateException::new); this.logger.logDatebackOperation(new PurgeKeyOperation(this.branch, keyspace, key, minTimestamp, maxTimestamp)); } @Override public void purgeKey(final String keyspace, final String key, final long purgeRangeStart, final long purgeRangeEnd) { checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); checkArgument(purgeRangeStart >= 0, "Precondition violation - argument 'purgeRangeStart' must not be negative!"); checkArgument(purgeRangeEnd >= purgeRangeStart, "Precondition violation - argument 'purgeRangeEnd' must be greater than or equal to 'purgeRangeStart'!"); this.assertNotClosed(); Collection<TemporalKey> changed = this.getTKVS().datebackPurgeKey(keyspace, key, purgeRangeStart, purgeRangeEnd); if(changed.isEmpty()){ return; } this.updateEarliestTouchedTimestamp(changed); long minTimestamp = changed.stream().mapToLong(TemporalKey::getTimestamp).min().orElseThrow(IllegalStateException::new); long maxTimestamp = changed.stream().mapToLong(TemporalKey::getTimestamp).max().orElseThrow(IllegalStateException::new); this.logger.logDatebackOperation(new PurgeKeyOperation(this.branch, keyspace, key, minTimestamp, maxTimestamp)); } @Override public void purgeKeyspace(final String keyspace, final long purgeRangeStart, final long purgeRangeEnd) { checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkArgument(purgeRangeStart >= 0, "Precondition violation - argument 'purgeRangeStart' must not be negative!"); checkArgument(purgeRangeEnd >= purgeRangeStart, "Precondition violation - argument 'purgeRangeEnd' must be greater than or equal to 'purgeRangeStart'!"); this.assertNotClosed(); Collection<TemporalKey> changed = this.getTKVS().datebackPurgeKeyspace(keyspace, purgeRangeStart, purgeRangeEnd); if(changed.isEmpty()){ return; } this.updateEarliestTouchedTimestamp(changed); long minTimestamp = changed.stream().mapToLong(TemporalKey::getTimestamp).min().orElseThrow(IllegalStateException::new); long maxTimestamp = changed.stream().mapToLong(TemporalKey::getTimestamp).max().orElseThrow(IllegalStateException::new); this.logger.logDatebackOperation(new PurgeKeyspaceOperation(this.branch, keyspace, minTimestamp, maxTimestamp)); } @Override public void purgeCommit(final long commitTimestamp) { checkArgument(commitTimestamp >= 0, "Precondition violation - argument 'commitTimestamp' must not be negative!"); this.assertNotClosed(); Collection<TemporalKey> changed = this.getTKVS().datebackPurgeCommit(commitTimestamp); this.updateEarliestTouchedTimestamp(changed); this.logger.logDatebackOperation(new PurgeCommitsOperation(this.branch, Collections.singleton(commitTimestamp))); } @Override public void purgeCommits(final long purgeRangeStart, final long purgeRangeEnd) { checkArgument(purgeRangeStart >= 0, "Precondition violation - argument 'purgeRangeStart' must not be negative!"); checkArgument(purgeRangeEnd >= purgeRangeStart, "Precondition violation - argument 'purgeRangeEnd' must be greater than or equal to 'purgeRangeStart'!"); this.assertNotClosed(); Collection<TemporalKey> changed = this.getTKVS().datebackPurgeCommits(purgeRangeStart, purgeRangeEnd); if(changed.isEmpty()){ return; } this.updateEarliestTouchedTimestamp(changed); Set<Long> timestamps = changed.stream().map(TemporalKey::getTimestamp).collect(Collectors.toSet()); logger.logDatebackOperation(new PurgeCommitsOperation(this.branch, timestamps)); } @Override public void inject(final String keyspace, final String key, final long timestamp, final Object value) { checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); this.assertNotClosed(); Collection<TemporalKey> changed = this.getTKVS().datebackInject(keyspace, key, timestamp, value); if(changed.isEmpty()){ return; } this.updateEarliestTouchedTimestamp(changed); this.logger.logDatebackOperation( new InjectEntriesOperation(this.branch, timestamp, Sets.newHashSet(QualifiedKey.create(keyspace, key)), false) ); } @Override public void inject(final String keyspace, final String key, final long timestamp, final Object value, final Object commitMetadata) { checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); this.assertNotClosed(); Collection<TemporalKey> changed = this.getTKVS().datebackInject(keyspace, key, timestamp, value, commitMetadata); if(changed.isEmpty()){ return; } this.updateEarliestTouchedTimestamp(changed); this.logger.logDatebackOperation( new InjectEntriesOperation(this.branch, timestamp, Sets.newHashSet(QualifiedKey.create(keyspace, key)), commitMetadata != null) ); } @Override public void inject(final String keyspace, final String key, final long timestamp, final Object value, final Object commitMetadata, final boolean overrideCommitMetadata) { checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); this.assertNotClosed(); Collection<TemporalKey> changed = this.getTKVS().datebackInject(keyspace, key, timestamp, value, commitMetadata, overrideCommitMetadata); if(changed.isEmpty()){ return; } this.updateEarliestTouchedTimestamp(changed); this.logger.logDatebackOperation( new InjectEntriesOperation(this.branch, timestamp, Sets.newHashSet(QualifiedKey.create(keyspace, key)), overrideCommitMetadata || commitMetadata != null) ); } @Override public void inject(final long timestamp, final Map<QualifiedKey, Object> entries) { checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); checkNotNull(entries, "Precondition violation - argument 'entries' must not be NULL!"); this.assertNotClosed(); Collection<TemporalKey> changed = this.getTKVS().datebackInject(timestamp, entries); if(changed == null || changed.isEmpty()){ return; } this.updateEarliestTouchedTimestamp(changed); this.logger.logDatebackOperation( new InjectEntriesOperation(this.branch, timestamp, changed.stream().map(TemporalKey::toQualifiedKey).collect(Collectors.toSet()), false) ); } @Override public void inject(final long timestamp, final Map<QualifiedKey, Object> entries, final Object commitMetadata) { checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); checkNotNull(entries, "Precondition violation - argument 'entries' must not be NULL!"); this.assertNotClosed(); Collection<TemporalKey> changed = this.getTKVS().datebackInject(timestamp, entries, commitMetadata); if(changed == null || changed.isEmpty()){ return; } this.updateEarliestTouchedTimestamp(changed); this.logger.logDatebackOperation( new InjectEntriesOperation(this.branch, timestamp, changed.stream().map(TemporalKey::toQualifiedKey).collect(Collectors.toSet()), commitMetadata != null) ); } @Override public void inject(final long timestamp, final Map<QualifiedKey, Object> entries, final Object commitMetadata, final boolean overrideCommitMetadata) { checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); checkNotNull(entries, "Precondition violation - argument 'entries' must not be NULL!"); this.assertNotClosed(); Collection<TemporalKey> changed = this.getTKVS().datebackInject(timestamp, entries, commitMetadata, overrideCommitMetadata); if(changed == null || changed.isEmpty()){ return; } this.updateEarliestTouchedTimestamp(changed); this.logger.logDatebackOperation( new InjectEntriesOperation(this.branch, timestamp, changed.stream().map(TemporalKey::toQualifiedKey).collect(Collectors.toSet()), overrideCommitMetadata || commitMetadata != null) ); } @Override public void transformEntry(final String keyspace, final String key, final long timestamp, final Function<Object, Object> transformation) { checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); checkNotNull(transformation, "Precondition violation - argument 'transformation' must not be NULL!"); this.assertNotClosed(); Collection<TemporalKey> changed = this.getTKVS().datebackTransformEntry(keyspace, key, timestamp, transformation); if(changed == null || changed.isEmpty()){ return; } this.updateEarliestTouchedTimestamp(changed); this.logger.logDatebackOperation(new TransformValuesOperation(this.branch, keyspace, key, Sets.newHashSet(timestamp))); } @Override public void transformValuesOfKey(final String keyspace, final String key, final BiFunction<Long, Object, Object> transformation) { checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); checkNotNull(transformation, "Precondition violation - argument 'transformation' must not be NULL!"); this.assertNotClosed(); Collection<TemporalKey> changed = this.getTKVS().datebackTransformValuesOfKey(keyspace, key, transformation); if(changed == null || changed.isEmpty()){ return; } this.updateEarliestTouchedTimestamp(changed); this.logger.logDatebackOperation( new TransformValuesOperation(this.branch, keyspace, key, changed.stream().map(TemporalKey::getTimestamp).collect(Collectors.toSet())) ); } @Override public void transformCommit(final long commitTimestamp, final Function<Map<QualifiedKey, Object>, Map<QualifiedKey, Object>> transformation) { checkArgument(commitTimestamp >= 0, "Precondition violation - argument 'commitTimestamp' must not be negative!"); checkNotNull(transformation, "Precondition violation - argument 'transformation' must not be NULL!"); this.assertNotClosed(); Collection<TemporalKey> changed = this.getTKVS().datebackTransformCommit(commitTimestamp, transformation); if(changed == null || changed.isEmpty()){ return; } this.updateEarliestTouchedTimestamp(changed); this.logger.logDatebackOperation( new TransformCommitOperation2(this.branch, commitTimestamp) ); } @Override public void transformValuesOfKeyspace(final String keyspace, final KeyspaceValueTransformation valueTransformation) { checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(valueTransformation, "Precondition violation - argument 'valueTransformation' must not be NULL!"); this.assertNotClosed(); Collection<TemporalKey> changed = this.getTKVS().datebackTransformValuesOfKeyspace(keyspace, valueTransformation); if(changed == null || changed.isEmpty()){ return; } this.updateEarliestTouchedTimestamp(changed); this.logger.logDatebackOperation( new TransformValuesOfKeyspaceOperation(this.branch, keyspace, changed.stream().mapToLong(TemporalKey::getTimestamp).min().orElse(Long.MAX_VALUE)) ); } @Override public void updateCommitMetadata(final long commitTimestamp, final Object newMetadata) { checkArgument(commitTimestamp >= 0, "Precondition violation - argument 'commitTimestamp' must not be negative!"); this.assertNotClosed(); this.getTKVS().datebackUpdateCommitMetadata(commitTimestamp, newMetadata); this.logger.logDatebackOperation(new UpdateCommitMetadataOperation(this.branch, commitTimestamp)); } @Override public void cleanup() { this.assertNotClosed(); if(this.earliestTouchedTimestamp == Long.MAX_VALUE){ // nothing touched return; } this.getTKVS().datebackCleanup(this.branch, this.earliestTouchedTimestamp); this.earliestTouchedTimestamp = Long.MAX_VALUE; } @Override public long getHighestUntouchedTimestamp() { // the highest untouched timestamp is always one lower than the lowest one we touched return this.earliestTouchedTimestamp - 1; } @Override public Object get(final long timestamp, final String keyspace, final String key) { this.assertTimestampWithinValidRange(timestamp); checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); return datebackSafeTx(timestamp).get(keyspace, key); } @Override public Set<String> keySet(final long timestamp, final String keyspace) { this.assertTimestampWithinValidRange(timestamp); checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); return this.datebackSafeTx(timestamp).keySet(keyspace); } @Override public Set<String> keyspaces(final long timestamp) { this.assertTimestampWithinValidRange(timestamp); return this.datebackSafeTx(timestamp).keyspaces(); } @Override public boolean isClosed() { return this.closed; } // ================================================================================================================= // INTERNAL HELPER METHODS // ================================================================================================================= private void assertTimestampWithinValidRange(long timestamp) { if (timestamp > this.getHighestUntouchedTimestamp()) { throw new IllegalArgumentException("Cannot query timestamp " + timestamp + ", as it has been influenced by a dateback operation already. The highest untouched timestamp is " + this.getHighestUntouchedTimestamp() + "."); } checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); } private ChronoDBTransaction datebackSafeTx(long timestamp) { this.assertTimestampWithinValidRange(timestamp); MutableTransactionConfiguration txConfig = new DefaultTransactionConfiguration(); txConfig.setBranch(this.branch); txConfig.setTimestamp(timestamp); txConfig.setReadOnly(true); txConfig.setAllowedDuringDateback(true); return this.db.tx(txConfig); } protected void assertNotClosed() { if (this.closed) { throw new IllegalStateException("Dateback process has already been terminated!"); } } protected TemporalKeyValueStore getTKVS() { BranchInternal branch = this.db.getBranchManager().getBranch(this.branch); TemporalKeyValueStore store = branch.getTemporalKeyValueStore(); return store; } protected void updateEarliestTouchedTimestamp(final long timestamp) { if(timestamp < this.earliestTouchedTimestamp){ this.earliestTouchedTimestamp = timestamp; } } protected void updateEarliestTouchedTimestamp(final Collection<TemporalKey> changSet) { for(TemporalKey key : changSet){ this.updateEarliestTouchedTimestamp(key.getTimestamp()); } } }
22,813
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
TransformValuesOfKeyspaceOperation.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dateback/log/TransformValuesOfKeyspaceOperation.java
package org.chronos.chronodb.internal.impl.dateback.log; import java.util.UUID; import static com.google.common.base.Preconditions.*; public class TransformValuesOfKeyspaceOperation extends AbstractDatebackOperation{ private String branch; private String keyspace; private long minChangedTimestamp; private TransformValuesOfKeyspaceOperation(){ // default constructor for deserialization } public TransformValuesOfKeyspaceOperation(final String id, final String branch, final long wallClockTime, final String keyspace, final long minChangedTimestamp){ super(id, branch, wallClockTime); checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkArgument(minChangedTimestamp >= 0, "Preconditino violation - argument 'minChangedTimestamp' must not be negative!"); this.branch = branch; this.keyspace = keyspace; this.minChangedTimestamp = minChangedTimestamp; } public TransformValuesOfKeyspaceOperation(final String branch, final String keyspace, final long minChangedTimestamp) { this(UUID.randomUUID().toString(), branch, System.currentTimeMillis(), keyspace, minChangedTimestamp); } public String getBranch() { return branch; } @Override public boolean affectsTimestamp(final long timestamp) { return this.minChangedTimestamp <= timestamp; } @Override public long getEarliestAffectedTimestamp() { return this.minChangedTimestamp; } public String getKeyspace() { return keyspace; } @Override public String toString() { final StringBuilder sb = new StringBuilder("TransformValuesOfKeyspaceOperation{"); sb.append("branch='").append(branch).append('\''); sb.append(", keyspace='").append(keyspace).append('\''); sb.append(", minChangedTimestamp=").append(minChangedTimestamp); sb.append('}'); return sb.toString(); } }
2,092
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
PurgeKeyOperation.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dateback/log/PurgeKeyOperation.java
package org.chronos.chronodb.internal.impl.dateback.log; import org.chronos.chronodb.internal.api.Period; import org.chronos.chronodb.internal.api.dateback.log.IPurgeKeyOperation; import java.util.UUID; import static com.google.common.base.Preconditions.*; public class PurgeKeyOperation extends AbstractDatebackOperation implements IPurgeKeyOperation { // ================================================================================================================= // FIELDS // ================================================================================================================= private String keyspace; private String key; private long fromTimestamp; private long toTimestamp; // ================================================================================================================= // CONSTRUCTORS // ================================================================================================================= public PurgeKeyOperation(){ // default constructor for (de-)serialization } public PurgeKeyOperation(String id, String branch, long wallClockTime, String keyspace, String key, long fromTimestamp, long toTimestamp){ super(id, branch, wallClockTime); checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); checkArgument(fromTimestamp >= 0, "Precondition violation - argument 'fromTimestamp' must not be negative!"); checkArgument(toTimestamp >= 0, "Precondition violation - argument 'toTimestamp' must not be negative!"); this.keyspace = keyspace; this.key = key; this.fromTimestamp = fromTimestamp; this.toTimestamp = toTimestamp; } public PurgeKeyOperation(String branch, String keyspace, String key, long fromTimestamp, long toTimestamp){ this(UUID.randomUUID().toString(), branch, System.currentTimeMillis(), keyspace, key, fromTimestamp, toTimestamp); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public long getEarliestAffectedTimestamp() { return this.fromTimestamp; } @Override public boolean affectsTimestamp(final long timestamp) { return timestamp >= this.fromTimestamp; } @Override public String getKeyspace() { return keyspace; } @Override public String getKey() { return key; } @Override public long getFromTimestamp() { return fromTimestamp; } @Override public long getToTimestamp() { return toTimestamp; } @Override public String toString() { return "PurgeKey[branch: " + this.getBranch() + ", wallClockTime: " + this.getWallClockTime() + ", purged: " + this.keyspace + "->" + this.key + ", period: " + Period.createRange(this.fromTimestamp, this.toTimestamp+1) + "]"; } }
3,187
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
PurgeEntryOperation.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dateback/log/PurgeEntryOperation.java
package org.chronos.chronodb.internal.impl.dateback.log; import org.chronos.chronodb.internal.api.dateback.log.IPurgeEntryOperation; import java.util.UUID; import static com.google.common.base.Preconditions.*; public class PurgeEntryOperation extends AbstractDatebackOperation implements IPurgeEntryOperation { // ================================================================================================================= // FIELDS // ================================================================================================================= private long operationTimestamp; private String keyspace; private String key; // ================================================================================================================= // CONSTRUCTORS // ================================================================================================================= protected PurgeEntryOperation() { // default constructor for (de-)serialization } public PurgeEntryOperation(String id, String branch, long wallClockTime, long operationTimestamp, String keyspace, String key) { super(id, branch, wallClockTime); checkArgument(operationTimestamp >= 0, "Precondition violation - argument 'operationTimestamp' must not be negative!"); checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); this.keyspace = keyspace; this.key = key; this.operationTimestamp = operationTimestamp; } public PurgeEntryOperation(String branch, long operationTimestamp, String keyspace, String key) { this(UUID.randomUUID().toString(), branch, System.currentTimeMillis(), operationTimestamp, keyspace, key); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public long getEarliestAffectedTimestamp() { return this.operationTimestamp; } @Override public boolean affectsTimestamp(final long timestamp) { return timestamp >= this.operationTimestamp; } @Override public String getKey() { return key; } @Override public String getKeyspace() { return keyspace; } @Override public long getOperationTimestamp() { return operationTimestamp; } @Override public String toString() { return "PurgeEntry[target: " + this.getBranch() + "@" + this.getOperationTimestamp() + ", wallClockTime: " + this.getWallClockTime() + ", purgedEntry: " + this.keyspace + "->" + this.key + "]"; } }
2,867
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
InjectEntriesOperation.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dateback/log/InjectEntriesOperation.java
package org.chronos.chronodb.internal.impl.dateback.log; import com.google.common.collect.Sets; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.internal.api.dateback.log.IInjectEntriesOperation; import java.util.Collections; import java.util.Set; import java.util.UUID; import static com.google.common.base.Preconditions.*; public class InjectEntriesOperation extends AbstractDatebackOperation implements IInjectEntriesOperation { // ================================================================================================================= // FIELDS // ================================================================================================================= private long operationTimestamp; private boolean commitMetadataOverride; private Set<QualifiedKey> injectedKeys = Collections.emptySet(); // ================================================================================================================= // CONSTRUCTORS // ================================================================================================================= protected InjectEntriesOperation(){ // default constructor for (de-)serialization } public InjectEntriesOperation(String id, String branch, long wallClockTime, long timestamp, Set<QualifiedKey> injectedKeys, boolean commitMetadataOverride){ super(id, branch, wallClockTime); checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); checkNotNull(injectedKeys, "Precondition violation - argument 'injectedKeys' must not be NULL!"); this.operationTimestamp = timestamp; this.commitMetadataOverride = commitMetadataOverride; this.injectedKeys = Sets.newHashSet(injectedKeys); } public InjectEntriesOperation(String branch, long timestamp, Set<QualifiedKey> injectedKeys, boolean commitMetadataOverride){ this(UUID.randomUUID().toString(), branch, System.currentTimeMillis(), timestamp, injectedKeys, commitMetadataOverride); } // ================================================================================================================= // PUBCIC API // ================================================================================================================= @Override public long getEarliestAffectedTimestamp() { return this.operationTimestamp; } @Override public boolean affectsTimestamp(final long timestamp) { return this.operationTimestamp <= timestamp; } @Override public long getOperationTimestamp() { return this.operationTimestamp; } @Override public boolean isCommitMetadataOverride() { return commitMetadataOverride; } public Set<QualifiedKey> getInjectedKeys() { return Collections.unmodifiableSet(injectedKeys); } @Override public String toString() { return "InjectEntries[target: " + this.getBranch() + "@" + this.getOperationTimestamp() + ", wallClockTime: " + this.getWallClockTime() + ", injectedKeys: " + this.getInjectedKeys().size() + "]"; } }
3,184
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
TransformValuesOperation.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dateback/log/TransformValuesOperation.java
package org.chronos.chronodb.internal.impl.dateback.log; import com.google.common.collect.Sets; import org.chronos.chronodb.internal.api.Period; import org.chronos.chronodb.internal.api.dateback.log.ITransformValuesOperation; import java.util.Collections; import java.util.Set; import java.util.UUID; import static com.google.common.base.Preconditions.*; public class TransformValuesOperation extends AbstractDatebackOperation implements ITransformValuesOperation { // ================================================================================================================= // FIELDS // ================================================================================================================= private Set<Long> commitTimestamps; private String keyspace; private String key; // ================================================================================================================= // CONSTRUCTORS // ================================================================================================================= protected TransformValuesOperation() { // default constructor for (de-)serialization } public TransformValuesOperation(String id, String branch, long wallClockTime, String keyspace, String key, Set<Long> commitTimestamps) { super(id, branch, wallClockTime); checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); checkNotNull(commitTimestamps, "Precondition violation - argument 'commitTimestamps' must not be NULL!"); checkArgument(commitTimestamps.stream().anyMatch(t -> t < 0), "Precondition violation - none of the provided 'commitTimestamps' must be negative!"); this.keyspace = keyspace; this.key = key; this.commitTimestamps = Sets.newHashSet(commitTimestamps); } public TransformValuesOperation(String branch, String keyspace, String key, Set<Long> commitTimestamps) { this(UUID.randomUUID().toString(), branch, System.currentTimeMillis(), keyspace, key, commitTimestamps); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public long getEarliestAffectedTimestamp() { // if we don't have any entries, the operation affects no timestamps at all -> we return MAX_VALUE (= infinity). return this.commitTimestamps.stream().mapToLong(t->t).min().orElse(Long.MAX_VALUE); } @Override public boolean affectsTimestamp(final long timestamp) { return this.commitTimestamps.stream().mapToLong(t -> t).min().orElseThrow(IllegalStateException::new) <= timestamp; } @Override public Set<Long> getCommitTimestamps() { return Collections.unmodifiableSet(commitTimestamps); } @Override public String getKeyspace() { return keyspace; } @Override public String getKey() { return key; } @Override public String toString() { long min = this.commitTimestamps.stream().mapToLong(l -> l).min().orElseThrow(IllegalStateException::new); long max = this.commitTimestamps.stream().mapToLong(l -> l).max().orElseThrow(IllegalStateException::new); if (max < Long.MAX_VALUE) { max += 1; // ranges render upper bound as exclusive, but our internal notation is inclusive } return "TransformValues[target: " + this.getBranch() + ", key: " + this.keyspace + "->" + this.key + " in " + this.commitTimestamps.size() + " timestamps in range " + Period.createRange(min, max) + "]"; } }
3,864
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
PurgeKeyspaceOperation.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dateback/log/PurgeKeyspaceOperation.java
package org.chronos.chronodb.internal.impl.dateback.log; import org.chronos.chronodb.internal.api.dateback.log.IPurgeKeyspaceOperation; import java.util.UUID; import static com.google.common.base.Preconditions.*; public class PurgeKeyspaceOperation extends AbstractDatebackOperation implements IPurgeKeyspaceOperation { // ================================================================================================================= // FIELDS // ================================================================================================================= private String keyspace; private long fromTimestamp; private long toTimestamp; // ================================================================================================================= // CONSTRUCTORS // ================================================================================================================= public PurgeKeyspaceOperation(){ // default constructor for (de-)serialization } public PurgeKeyspaceOperation(final String id, final String branch, final long wallClockTime, final String keyspace, final long fromTimestamp, final long toTimestamp){ super(id, branch, wallClockTime); checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkArgument(fromTimestamp >= 0, "Precondition violation - argument 'fromTimestamp' must not be negative!"); checkArgument(toTimestamp >= 0, "Precondition violation - argument 'toTimestamp' must not be negative!"); this.keyspace = keyspace; this.fromTimestamp = fromTimestamp; this.toTimestamp = toTimestamp; } public PurgeKeyspaceOperation(final String branch, final String keyspace, final long fromTimestamp, final long toTimestamp){ this(UUID.randomUUID().toString(), branch, System.currentTimeMillis(), keyspace, fromTimestamp, toTimestamp); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public long getEarliestAffectedTimestamp() { return this.fromTimestamp; } @Override public boolean affectsTimestamp(final long timestamp) { return timestamp >= this.fromTimestamp; } @Override public String getKeyspace() { return keyspace; } @Override public long getFromTimestamp() { return fromTimestamp; } @Override public long getToTimestamp() { return toTimestamp; } @Override public String toString() { final StringBuilder sb = new StringBuilder("PurgeKeyspaceOperation{"); sb.append("keyspace='").append(keyspace).append('\''); sb.append(", fromTimestamp=").append(fromTimestamp); sb.append(", toTimestamp=").append(toTimestamp); sb.append('}'); return sb.toString(); } }
3,072
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
TransformCommitOperation.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dateback/log/TransformCommitOperation.java
package org.chronos.chronodb.internal.impl.dateback.log; import com.google.common.collect.Sets; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.internal.api.dateback.log.ITransformCommitOperation; import org.chronos.chronodb.internal.impl.dateback.log.v2.TransformCommitOperation2; import java.util.Collections; import java.util.Set; import java.util.UUID; import static com.google.common.base.Preconditions.*; /** * This class has been deprecated in favour of {@link TransformCommitOperation2}. * * <p> * We still keep it here for backwards compatibility / deserialization purposes. * </p> */ @Deprecated public class TransformCommitOperation extends AbstractDatebackOperation implements ITransformCommitOperation { // ================================================================================================================= // FIELDS // ================================================================================================================= private long commitTimestamp; private Set<QualifiedKey> changedKeys; // ================================================================================================================= // CONSTRUCTORS // ================================================================================================================= protected TransformCommitOperation(){ // default constructor for (de-)serialization } public TransformCommitOperation(String id, String branch, long wallClockTime, long commitTimestamp, Set<QualifiedKey> changedKeys) { super(id, branch, wallClockTime); checkArgument(commitTimestamp >= 0, "Precondition violation - argument 'commitTimestamp' must not be negative!"); checkNotNull(changedKeys, "Precondition violation - argument 'changedKeys' must not be NULL!"); this.commitTimestamp = commitTimestamp; this.changedKeys = Sets.newHashSet(changedKeys); } public TransformCommitOperation(String branch, long commitTimestamp, Set<QualifiedKey> changedKeys) { this(UUID.randomUUID().toString(), branch, System.currentTimeMillis(), commitTimestamp, changedKeys); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public long getEarliestAffectedTimestamp() { return this.commitTimestamp; } @Override public boolean affectsTimestamp(final long timestamp) { return timestamp >= this.commitTimestamp; } @Override public long getCommitTimestamp() { return commitTimestamp; } public Set<QualifiedKey> getChangedKeys() { return Collections.unmodifiableSet(changedKeys); } @Override public String toString() { return "TransformCommit[target: " + this.getBranch() + "@" + this.getCommitTimestamp() + ", wallClockTime: " + this.getWallClockTime() + ", changedKeys: " + this.changedKeys.size() + "]"; } }
3,153
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
UpdateCommitMetadataOperation.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dateback/log/UpdateCommitMetadataOperation.java
package org.chronos.chronodb.internal.impl.dateback.log; import org.chronos.chronodb.internal.api.dateback.log.IUpdateCommitMetadataOperation; import java.util.UUID; public class UpdateCommitMetadataOperation extends AbstractDatebackOperation implements IUpdateCommitMetadataOperation { // ================================================================================================================= // FIELDS // ================================================================================================================= private long commitTimestamp; // ================================================================================================================= // CONSTRUCTORS // ================================================================================================================= protected UpdateCommitMetadataOperation(){ // default constructor for (de-)serialization } public UpdateCommitMetadataOperation(String id, String branch, long wallClockTime, long commitTimestamp){ super(id, branch, wallClockTime); this.commitTimestamp = commitTimestamp; } public UpdateCommitMetadataOperation(String branch, long commitTimestamp){ this(UUID.randomUUID().toString(), branch, System.currentTimeMillis(), commitTimestamp); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public long getEarliestAffectedTimestamp() { return this.commitTimestamp; } @Override public boolean affectsTimestamp(final long timestamp) { // changes on the commit metadata only affect the commit itself, not the future return this.commitTimestamp == timestamp; } @Override public long getCommitTimestamp() { return commitTimestamp; } @Override public String toString() { return "UpdateCommitMetadata[target: " + this.getBranch() + "@" + this.commitTimestamp + ", wallClockTime: " + this.getWallClockTime() + "]"; } }
2,228
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AbstractDatebackOperation.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dateback/log/AbstractDatebackOperation.java
package org.chronos.chronodb.internal.impl.dateback.log; import org.chronos.chronodb.internal.api.dateback.log.DatebackOperation; import java.util.UUID; import static com.google.common.base.Preconditions.*; public abstract class AbstractDatebackOperation implements DatebackOperation { // ================================================================================================================= // FIELDS // ================================================================================================================= private String id; private long wallClockTime; private String branch; // ================================================================================================================= // CONSTRUCTORS // ================================================================================================================= protected AbstractDatebackOperation(){ // default constructor for (de-)serialization } protected AbstractDatebackOperation(String id, String branch, long wallClockTime){ checkNotNull(id, "Precondition violation - argument 'id' must not be NULL!"); checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); checkArgument(wallClockTime >= 0, "Precondition violation - argument 'wallClockTime' must not be negative!"); this.id = id; this.branch = branch; this.wallClockTime = wallClockTime; } protected AbstractDatebackOperation(String branch){ this(UUID.randomUUID().toString(), branch, System.currentTimeMillis()); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public String getId(){ return this.id; } @Override public long getWallClockTime() { return this.wallClockTime; } @Override public String getBranch() { return this.branch; } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AbstractDatebackOperation that = (AbstractDatebackOperation) o; return id != null ? id.equals(that.id) : that.id == null; } @Override public int hashCode() { return id != null ? id.hashCode() : 0; } }
2,565
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
PurgeCommitsOperation.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dateback/log/PurgeCommitsOperation.java
package org.chronos.chronodb.internal.impl.dateback.log; import com.google.common.collect.Sets; import org.chronos.chronodb.internal.api.dateback.log.IPurgeCommitsOperation; import java.util.Collections; import java.util.Set; import java.util.UUID; import java.util.function.Function; import static com.google.common.base.Preconditions.*; public class PurgeCommitsOperation extends AbstractDatebackOperation implements IPurgeCommitsOperation { // ================================================================================================================= // FIELDS // ================================================================================================================= private Set<Long> commitTimestamps; // ================================================================================================================= // CONSTRUCTORS // ================================================================================================================= protected PurgeCommitsOperation(){ // default constructor for (de-)serialization } public PurgeCommitsOperation(String id, String branch, long wallClockTime, Set<Long> commitTimestamps){ super(id, branch, wallClockTime); checkNotNull(commitTimestamps, "Precondition violation - argument 'commitTimestamps' must not be NULL!"); commitTimestamps.forEach(t -> checkArgument(t >= 0, "Precondition violation - argument 'commitTimestamps' must not contain negative values!")); this.commitTimestamps = Sets.newHashSet(commitTimestamps); } public PurgeCommitsOperation(String branch, Set<Long> commitTimestamps){ this(UUID.randomUUID().toString(), branch, System.currentTimeMillis(), commitTimestamps); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public long getEarliestAffectedTimestamp() { // if we don't have any entries, the operation affects no timestamps at all -> we return MAX_VALUE (= infinity). return this.commitTimestamps.stream().mapToLong(t->t).min().orElse(Long.MAX_VALUE); } @Override public boolean affectsTimestamp(final long timestamp) { return timestamp >= this.commitTimestamps.stream().mapToLong(t -> t).min().orElse(Long.MAX_VALUE); } @Override public Set<Long> getCommitTimestamps() { return Collections.unmodifiableSet(this.commitTimestamps); } @Override public String toString() { return "PurgeCommits[branch: " + this.getBranch() + ", wallClockTime: " + this.getWallClockTime() + ", timestamps: " + this.commitTimestamps+ "]"; } }
2,856
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
TransformCommitOperation2.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dateback/log/v2/TransformCommitOperation2.java
package org.chronos.chronodb.internal.impl.dateback.log.v2; import org.chronos.chronodb.internal.api.dateback.log.ITransformCommitOperation; import org.chronos.chronodb.internal.impl.dateback.log.AbstractDatebackOperation; import java.util.UUID; import static com.google.common.base.Preconditions.*; public class TransformCommitOperation2 extends AbstractDatebackOperation implements ITransformCommitOperation { // ================================================================================================================= // FIELDS // ================================================================================================================= private long commitTimestamp; // ================================================================================================================= // CONSTRUCTORS // ================================================================================================================= protected TransformCommitOperation2(){ // default constructor for (de-)serialization } public TransformCommitOperation2(String id, String branch, long wallClockTime, long commitTimestamp) { super(id, branch, wallClockTime); checkArgument(commitTimestamp >= 0, "Precondition violation - argument 'commitTimestamp' must not be negative!"); this.commitTimestamp = commitTimestamp; } public TransformCommitOperation2(String branch, long commitTimestamp) { this(UUID.randomUUID().toString(), branch, System.currentTimeMillis(), commitTimestamp); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public long getEarliestAffectedTimestamp() { return this.commitTimestamp; } @Override public boolean affectsTimestamp(final long timestamp) { return timestamp >= this.commitTimestamp; } @Override public long getCommitTimestamp() { return commitTimestamp; } @Override public String toString() { return "TransformCommit[target: " + this.getBranch() + "@" + this.getCommitTimestamp() + ", wallClockTime: " + this.getWallClockTime() + "]"; } }
2,377
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
TransformingCloseableIterator.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/stream/TransformingCloseableIterator.java
package org.chronos.chronodb.internal.impl.stream; import static com.google.common.base.Preconditions.*; import java.util.function.Function; import org.chronos.chronodb.internal.api.stream.CloseableIterator; public class TransformingCloseableIterator<E, F> extends AbstractCloseableIterator<F> { private final CloseableIterator<E> iterator; private final Function<? super E, ? extends F> function; public TransformingCloseableIterator(final CloseableIterator<E> iterator, final Function<? super E, ? extends F> function) { checkNotNull(function, "Precondition violation - argument 'function' must not be NULL!"); this.iterator = iterator; this.function = function; } @Override public F next() { return this.function.apply(this.iterator.next()); } @Override protected boolean hasNextInternal() { return this.iterator.hasNext(); } @Override protected void closeInternal() { this.iterator.close(); } }
937
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AbstractCloseableIterator.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/stream/AbstractCloseableIterator.java
package org.chronos.chronodb.internal.impl.stream; import org.chronos.chronodb.internal.api.stream.CloseableIterator; public abstract class AbstractCloseableIterator<T> implements CloseableIterator<T> { private boolean closed; @Override public final boolean hasNext() { if (this.closed) { return false; } return this.hasNextInternal(); } @Override public final void close() { if (this.isClosed()) { return; } this.closeInternal(); this.closed = true; } @Override public final boolean isClosed() { return this.closed; } protected abstract boolean hasNextInternal(); protected abstract void closeInternal(); }
651
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ConcatenatedCloseableIterator.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/stream/ConcatenatedCloseableIterator.java
package org.chronos.chronodb.internal.impl.stream; import static com.google.common.base.Preconditions.*; import java.util.Iterator; import java.util.NoSuchElementException; import org.chronos.chronodb.internal.api.stream.CloseableIterator; public class ConcatenatedCloseableIterator<T> extends AbstractCloseableIterator<T> { private final Iterator<CloseableIterator<T>> iterator; private CloseableIterator<T> currentIterator; public ConcatenatedCloseableIterator(final Iterator<CloseableIterator<T>> iterator) { checkNotNull(iterator, "Precondition violation - argument 'iterator' must not be NULL!"); this.iterator = iterator; if (iterator.hasNext()) { this.currentIterator = iterator.next(); } else { this.currentIterator = null; } } @Override protected boolean hasNextInternal() { if (this.currentIterator != null && this.currentIterator.hasNext()) { // there are remaining entries in our current iterator return true; } // the current stream is empty, move to the next stream boolean foundNextIterator = this.moveToNextIterator(); if (foundNextIterator) { // we have loaded the next non-empty iterator return true; } else { // there are no more iterators... return false; } } @Override public T next() { if (this.hasNext() == false) { throw new NoSuchElementException(); } return this.currentIterator.next(); } @Override protected void closeInternal() { if (this.currentIterator != null) { this.currentIterator.close(); } } // ===================================================================================================================== // INTERNAL HELPER METHODS // ===================================================================================================================== private boolean moveToNextIterator() { // close the current iterator (if any) if (this.currentIterator != null) { this.currentIterator.close(); } while (true) { if (this.iterator.hasNext() == false) { // no more streams avaliable this.currentIterator = null; return false; } CloseableIterator<T> nextIterator = this.iterator.next(); if (nextIterator.hasNext() == false) { // iterator is empty; close it and move to the next nextIterator.close(); } else { // this is our next iterator this.currentIterator = nextIterator; return true; } } } }
2,394
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoDBEntryImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/stream/entry/ChronoDBEntryImpl.java
package org.chronos.chronodb.internal.impl.stream.entry; import static com.google.common.base.Preconditions.*; import org.chronos.chronodb.api.key.ChronoIdentifier; import org.chronos.chronodb.internal.api.stream.ChronoDBEntry; public class ChronoDBEntryImpl implements ChronoDBEntry { // ===================================================================================================================== // STATIC FACTORY // ===================================================================================================================== public static ChronoDBEntryImpl create(final ChronoIdentifier identifier, final byte[] value) { checkNotNull(identifier, "Precondition violation - argument 'identifier' must not be NULL!"); return new ChronoDBEntryImpl(identifier, value); } // ===================================================================================================================== // FIELDS // ===================================================================================================================== private final ChronoIdentifier identifier; private final byte[] value; // ===================================================================================================================== // CONSTRUCTOR // ===================================================================================================================== protected ChronoDBEntryImpl(final ChronoIdentifier identifier, final byte[] value) { checkNotNull(identifier, "Precondition violation - argument 'identifier' must not be NULL!"); this.identifier = identifier; this.value = value; } // ===================================================================================================================== // PUBLIC API // ===================================================================================================================== @Override public ChronoIdentifier getIdentifier() { return this.identifier; } @Override public byte[] getValue() { return this.value; } @Override public String toString() { return "ChronoEntry[key=" + this.identifier + ", value=byte[" + this.value.length + "]"; } }
2,176
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
DocumentBasedIndexManager.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/index/DocumentBasedIndexManager.java
package org.chronos.chronodb.internal.impl.index; import com.google.common.collect.ListMultimap; import com.google.common.collect.Maps; import com.google.common.collect.Multimaps; import com.google.common.collect.SetMultimap; import org.apache.commons.lang3.tuple.Pair; import org.chronos.chronodb.api.*; import org.chronos.chronodb.api.key.ChronoIdentifier; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.inmemory.InMemoryIndexManagerBackend; import org.chronos.chronodb.internal.api.BranchInternal; import org.chronos.chronodb.internal.api.ChronoDBInternal; import org.chronos.chronodb.internal.api.TemporalKeyValueStore; import org.chronos.chronodb.internal.api.index.ChronoIndexDocument; import org.chronos.chronodb.internal.api.index.ChronoIndexDocumentModifications; import org.chronos.chronodb.internal.api.index.DocumentAddition; import org.chronos.chronodb.internal.api.query.searchspec.SearchSpecification; import org.chronos.chronodb.internal.api.stream.ChronoDBEntry; import org.chronos.chronodb.internal.api.stream.CloseableIterator; import org.chronos.chronodb.internal.impl.index.cursor.IndexScanCursor; import org.chronos.chronodb.internal.impl.index.diff.IndexValueDiff; import org.chronos.chronodb.internal.impl.index.diff.IndexingUtils; import org.chronos.common.autolock.AutoLock; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.Map.Entry; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.*; public class DocumentBasedIndexManager extends AbstractIndexManager<ChronoDBInternal> { private InMemoryIndexManagerBackend backend; // ===================================================================================================================== // CONSTRUCTOR // ===================================================================================================================== public DocumentBasedIndexManager(final ChronoDBInternal owningDB) { super(owningDB); this.backend = new InMemoryIndexManagerBackend(owningDB); this.initializeIndicesFromDisk(); } // ================================================================================================================= // INDEX MANAGEMENT METHODS // ================================================================================================================= @NotNull @Override public Set<SecondaryIndexImpl> loadIndicesFromPersistence() { return this.backend.loadIndexersFromPersistence(); } @Override public void deleteIndexInternal(@NotNull final SecondaryIndexImpl index) { this.backend.deleteIndexContentsAndIndex(index); } @Override public void deleteAllIndicesInternal() { this.backend.deleteAllIndicesAndIndexers(); } @Override public void saveIndexInternal(@NotNull final SecondaryIndexImpl index) { this.backend.persistIndex(index); } @Override public void rollback(@NotNull final SecondaryIndexImpl index, final long timestamp) { this.backend.rollback(Collections.singleton(index), timestamp); } @Override @SuppressWarnings({"unchecked", "rawtypes"}) public void rollback(@NotNull final Set<SecondaryIndexImpl> indices, final long timestamp) { this.backend.rollback((Set) indices, timestamp); } @Override @SuppressWarnings({"rawtypes", "unchecked"}) public void rollback(@NotNull final Set<SecondaryIndexImpl> indices, final long timestamp, @NotNull final Set<? extends QualifiedKey> keys) { this.backend.rollback((Set) indices, timestamp, (Set) keys); } @Override public void saveIndicesInternal(@NotNull final Set<SecondaryIndexImpl> indices) { this.backend.persistIndexers(indices); } // ================================================================================================================= // INDEXING METHODS // ================================================================================================================= @Override @SuppressWarnings({"unchecked", "rawtypes"}) public void reindexAll(final boolean force) { try (AutoLock lock = this.getOwningDB().lockExclusive()) { Set<SecondaryIndex> indices; if (force) { indices = this.getOwningDB().getIndexManager().getIndices(); // drop ALL index files (more efficient implementation than the override with 'dirtyIndices' parameter) this.backend.deleteAllIndexContents(); } else { indices = this.getOwningDB().getIndexManager().getDirtyIndices(); // delete all index data we have for those indices indices.forEach(this.backend::deleteIndexContents); } this.createIndexBaselines(indices); ListMultimap<String, SecondaryIndex> indicesByBranch = Multimaps.index(indices, SecondaryIndex::getBranch); Set<BranchInternal> branches = indicesByBranch.keySet().stream().map(b -> this.getOwningDB().getBranchManager().getBranch(b)).collect(Collectors.toSet()); // then, iterate over the contents of the database Map<ChronoIdentifier, Pair<Object, Object>> identifierToValue = Maps.newHashMap(); SerializationManager serializationManager = this.getOwningDB().getSerializationManager(); for (BranchInternal branch : branches) { TemporalKeyValueStore tkvs = branch.getTemporalKeyValueStore(); long now = tkvs.getNow(); try (CloseableIterator<ChronoDBEntry> entries = tkvs.allEntriesIterator(0, now)) { while (entries.hasNext()) { ChronoDBEntry entry = entries.next(); ChronoIdentifier identifier = entry.getIdentifier(); byte[] value = entry.getValue(); Object deserializedValue = null; if (value != null && value.length > 0) { // only deserialize if the stored value is non-null deserializedValue = serializationManager.deserialize(value); } ChronoDBTransaction historyTx = tkvs.tx(branch.getName(), identifier.getTimestamp() - 1); Object historyValue = historyTx.get(identifier.getKeyspace(), identifier.getKey()); identifierToValue.put(identifier, Pair.of(historyValue, deserializedValue)); } } } this.index(identifierToValue, indices); // clear the query cache this.clearQueryCache(); this.getOwningDB().getStatisticsManager().clearBranchHeadStatistics(); for (SecondaryIndex index : indices) { ((SecondaryIndexImpl) index).setDirty(false); } this.saveIndicesInternal((Set) indices); } } private void createIndexBaselines(final Set<SecondaryIndex> indices) { if (indices.isEmpty()) { return; } Set<SecondaryIndex> unbasedIndices = indices.stream() // do not include inherited indices (for those we need no baseline, because the queries // will be redirected to the parent index anyways). .filter(idx -> idx.getParentIndexId() == null) // only consider the indices on non-master branches .filter(idx -> !idx.getBranch().equals(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER)) .collect(Collectors.toSet()); if (unbasedIndices.isEmpty()) { return; } ListMultimap<String, SecondaryIndex> indicesByBranch = Multimaps.index(indices, SecondaryIndex::getBranch); for (Entry<String, Collection<SecondaryIndex>> branchToIndices : indicesByBranch.asMap().entrySet()) { String branch = branchToIndices.getKey(); Collection<SecondaryIndex> branchIndices = branchToIndices.getValue(); ListMultimap<Long, SecondaryIndex> unbasedIndexGroup = Multimaps.index(branchIndices, idx -> idx.getValidPeriod().getLowerBound()); for (Entry<Long, Collection<SecondaryIndex>> entry : unbasedIndexGroup.asMap().entrySet()) { Long startTimestamp = entry.getKey(); Collection<SecondaryIndex> indicesInGroup = entry.getValue(); ChronoDBTransaction chronoDbTransaction = this.getOwningDB().tx(branch, startTimestamp); for (String keyspace : chronoDbTransaction.keyspaces()) { Set<String> keySet = chronoDbTransaction.keySet(keyspace); for (String key : keySet) { ChronoIndexDocumentModifications modifications = ChronoIndexDocumentModifications.create(); Object value = chronoDbTransaction.get(keyspace, key); if (value == null) { continue; // safeguard, can't happen } for (SecondaryIndex index : indicesInGroup) { Set<Comparable<?>> indexValues = index.getIndexedValuesForObject(value); for (Object indexValue : indexValues) { modifications.addDocumentCreation(DocumentAddition.create( ChronoIdentifier.create(branch, startTimestamp, keyspace, key), index, indexValue )); } } this.backend.applyModifications(modifications); } } } } } @Override public void index(@NotNull final Map<ChronoIdentifier, ? extends Pair<Object, Object>> identifierToOldAndNewValue) { checkNotNull(identifierToOldAndNewValue, "Precondition violation - argument 'identifierToOldAndNewValue' must not be NULL!"); Set<SecondaryIndex> indices = this.indexTree.getAllIndices().stream() .filter(idx -> !idx.getDirty()).collect(Collectors.toSet()); this.index(identifierToOldAndNewValue, indices); } @SuppressWarnings("unchecked") public void index(@NotNull final Map<ChronoIdentifier, ? extends Pair<Object, Object>> identifierToOldAndNewValue, Set<SecondaryIndex> indices) { checkNotNull(identifierToOldAndNewValue, "Precondition violation - argument 'identifierToOldAndNewValue' must not be NULL!"); checkNotNull(indices, "Precondition violation - argument 'indices' must not be NULL!"); if (indices.isEmpty() || identifierToOldAndNewValue.isEmpty()) { return; } try (AutoLock lock = this.getOwningDB().lockNonExclusive()) { new IndexingProcess(indices).index((Map<ChronoIdentifier, Pair<Object, Object>>) identifierToOldAndNewValue); } } // ===================================================================================================================== // QUERY METHODS // ===================================================================================================================== @NotNull @Override public Set<String> performIndexQuery( final long timestamp, @NotNull final Branch branch, @NotNull final String keyspace, final SearchSpecification<?, ?> searchSpec ) { try (AutoLock lock = this.getOwningDB().lockNonExclusive()) { // check if we are dealing with a negated search specification that accepts empty values. if (searchSpec.getCondition().isNegated() && searchSpec.getCondition().acceptsEmptyValue()) { // the search spec is a negated condition that accepts the empty value. // To resolve this condition: // - Call keySet() on the target keyspace // - query the index with the non-negated condition // - subtract the matches from the keyset Set<String> keySet = this.getOwningDB().tx(branch.getName(), timestamp).keySet(keyspace); SearchSpecification<?, ?> nonNegatedSearch = searchSpec.negate(); Collection<ChronoIndexDocument> documents = this.backend .getMatchingDocuments(timestamp, branch, keyspace, nonNegatedSearch); // subtract the matches from the keyset for (ChronoIndexDocument document : documents) { String key = document.getKey(); keySet.remove(key); } return Collections.unmodifiableSet(keySet); } else { Collection<ChronoIndexDocument> documents = this.backend .getMatchingDocuments(timestamp, branch, keyspace, searchSpec); return Collections .unmodifiableSet(documents.stream().map(ChronoIndexDocument::getKey).collect(Collectors.toSet())); } } } @NotNull @Override protected IndexScanCursor<?> createCursorInternal( @NotNull final Branch branch, final long timestamp, @NotNull final SecondaryIndex index, @NotNull final String keyspace, @NotNull final String indexName, @NotNull final Order order, @NotNull final TextCompare textCompare, @Nullable final Set<String> keys ) { checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); checkNotNull(index, "Precondition violation - argument 'index' must not be NULL!"); checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(indexName, "Precondition violation - argument 'indexName' must not be NULL!"); checkNotNull(order, "Precondition violation - argument 'order' must not be NULL!"); checkNotNull(textCompare, "Precondition violation - argument 'textCompare' must not be NULL!"); return this.backend.createCursorOnIndex( branch, timestamp, index, keyspace, indexName, order, textCompare, keys ); } // ===================================================================================================================== // INNER CLASSES // ===================================================================================================================== private class IndexingProcess { private final Set<SecondaryIndex> indices; private long currentTimestamp = -1L; private ChronoIndexDocumentModifications indexModifications; private Branch branch; IndexingProcess(Set<SecondaryIndex> indices) { this.indices = indices; } public void index(final Map<ChronoIdentifier, Pair<Object, Object>> identifierToValue) { checkNotNull(identifierToValue, "Precondition violation - argument 'identifierToValue' must not be NULL!"); // build the indexer workload. The primary purpose is to sort the entries of the map in an order suitable // for processing. List<Pair<ChronoIdentifier, Pair<Object, Object>>> workload = IndexerWorkloadSorter.sort(identifierToValue); // get the iterator over the workload Iterator<Pair<ChronoIdentifier, Pair<Object, Object>>> iterator = workload.iterator(); ListMultimap<String, SecondaryIndex> indicesByBranch = Multimaps.index(this.indices, SecondaryIndex::getBranch); // iterate over the workload while (iterator.hasNext()) { Pair<ChronoIdentifier, Pair<Object, Object>> entry = iterator.next(); // unwrap the chrono identifier and the value to index associated with it ChronoIdentifier chronoIdentifier = entry.getKey(); // check if we need to perform any periodic tasks this.checkCurrentTimestamp(chronoIdentifier.getTimestamp()); this.checkCurrentBranch(chronoIdentifier.getBranchName()); // index the single entry Pair<Object, Object> oldAndNewValue = identifierToValue.get(chronoIdentifier); Object oldValue = oldAndNewValue.getLeft(); Object newValue = oldAndNewValue.getRight(); List<SecondaryIndex> indices = indicesByBranch.get(chronoIdentifier.getBranchName()); Set<SecondaryIndex> filteredIndices = indices.stream() .filter(index -> !index.getValidPeriod().isBefore(chronoIdentifier.getTimestamp())) .collect(Collectors.toSet()); this.indexSingleEntry(chronoIdentifier, oldValue, newValue, filteredIndices); } // apply any remaining index modifications if (this.indexModifications.isEmpty() == false) { DocumentBasedIndexManager.this.backend.applyModifications(this.indexModifications); } } private void checkCurrentBranch(final String nextBranchName) { if (this.branch == null || this.branch.getName().equals(nextBranchName) == false) { // the branch is not the same as in the previous entry. Fetch the // branch metadata from the database. this.branch = DocumentBasedIndexManager.this.getOwningDB().getBranchManager().getBranch(nextBranchName); } } private void checkCurrentTimestamp(final long nextTimestamp) { if (this.currentTimestamp < 0 || this.currentTimestamp != nextTimestamp) { // the timestamp of the new work item is different from the one before. We need // to apply any index modifications (if any) and open a new modifications object if (this.indexModifications != null) { DocumentBasedIndexManager.this.backend.applyModifications(this.indexModifications); } this.currentTimestamp = nextTimestamp; this.indexModifications = ChronoIndexDocumentModifications.create(); } } private void indexSingleEntry(final ChronoIdentifier chronoIdentifier, final Object oldValue, final Object newValue, final Set<SecondaryIndex> secondaryIndices) { // in order to correctly treat the deletions, we need to query the index backend for // the currently active documents. We load these on-demand, because we don't need them in // the common case of indexing previously unseen (new) elements. Map<SecondaryIndex, SetMultimap<Object, ChronoIndexDocument>> oldDocuments = null; // calculate the diff IndexValueDiff diff = IndexingUtils.calculateDiff(secondaryIndices, oldValue, newValue); for (SecondaryIndex index : diff.getChangedIndices()) { Set<Object> addedValues = diff.getAdditions(index); Set<Object> removedValues = diff.getRemovals(index); // for each value we need to add, we create an index document based on the ChronoIdentifier. for (Object addedValue : addedValues) { this.indexModifications.addDocumentAddition(chronoIdentifier, index, addedValue); } // iterate over the removed values and terminate the document validities for (Object removedValue : removedValues) { if (oldDocuments == null) { // make sure that the current index documents are available oldDocuments = DocumentBasedIndexManager.this.backend .getMatchingBranchLocalDocuments(chronoIdentifier); } SetMultimap<Object, ChronoIndexDocument> indexedValueToOldDoc = oldDocuments.get(index); if (indexedValueToOldDoc == null) { // There is no document for the old index value in our branch. This means that this indexed // value was never touched in our branch. To "simulate" a valdity termination, we // insert a new index document which is valid from the creation of our branch until // our current timestamp. ChronoIndexDocument document = new ChronoIndexDocumentImpl(index, this.branch.getName(), chronoIdentifier.getKeyspace(), chronoIdentifier.getKey(), removedValue, this.branch.getBranchingTimestamp()); document.setValidToTimestamp(this.currentTimestamp); this.indexModifications.addDocumentAddition(document); } else { Set<ChronoIndexDocument> oldDocs = indexedValueToOldDoc.get(removedValue); for (ChronoIndexDocument oldDocument : oldDocs) { if (oldDocument.getValidToTimestamp() < Long.MAX_VALUE) { // the document has already been closed. This can happen if a key-value pair has // been inserted into the store, later deleted, and later re-inserted. continue; } else { // the document belongs to our branch; terminate its validity this.terminateDocumentValidityOrDeleteDocument(oldDocument, this.currentTimestamp); } } } } } } private void terminateDocumentValidityOrDeleteDocument(final ChronoIndexDocument document, final long timestamp) { checkNotNull(document, "Precondition violation - argument 'document' must not be NULL!"); checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); // check when the document was created if (document.getValidFromTimestamp() >= timestamp) { // the document was created at the same timestamp where we are going // to terminate it. That makes no sense, because the time ranges are // inclusive in the lower bound and exclusive in the upper bound. // Therefore, if lowerbound == upper bound, then the document needs // to be deleted instead. This situation can appear during incremental // commits. this.indexModifications.addDocumentDeletion(document); } else { // regularly terminate the validity of this document this.indexModifications.addDocumentValidityTermination(document, timestamp); } } } }
23,372
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
DocumentDeletionImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/index/DocumentDeletionImpl.java
package org.chronos.chronodb.internal.impl.index; import static com.google.common.base.Preconditions.*; import org.chronos.chronodb.internal.api.index.ChronoIndexDocument; import org.chronos.chronodb.internal.api.index.DocumentDeletion; public class DocumentDeletionImpl implements DocumentDeletion { private final ChronoIndexDocument documentToDelete; public DocumentDeletionImpl(final ChronoIndexDocument documentToDelete) { checkNotNull(documentToDelete, "Precondition violation - argument 'documentToDelete' must not be NULL!"); this.documentToDelete = documentToDelete; } @Override public ChronoIndexDocument getDocumentToDelete() { return this.documentToDelete; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.documentToDelete == null ? 0 : this.documentToDelete.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (obj instanceof DocumentDeletion == false) { return false; } DocumentDeletion other = (DocumentDeletion) obj; if (this.documentToDelete == null) { if (other.getDocumentToDelete() != null) { return false; } } else if (!this.documentToDelete.equals(other.getDocumentToDelete())) { return false; } return true; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("DELETE("); builder.append(this.documentToDelete.getIndex()); builder.append("->"); builder.append(this.documentToDelete.getKeyspace()); builder.append("->"); builder.append(this.documentToDelete.getKey()); builder.append("->"); builder.append(this.documentToDelete.getIndexedValue()); builder.append(")"); return builder.toString(); } }
1,830
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
IndexerWorkloadSorter.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/index/IndexerWorkloadSorter.java
package org.chronos.chronodb.internal.impl.index; import static com.google.common.base.Preconditions.*; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.lang3.tuple.Pair; import org.chronos.chronodb.api.key.ChronoIdentifier; import com.google.common.collect.Lists; public class IndexerWorkloadSorter { public static List<Pair<ChronoIdentifier, Pair<Object, Object>>> sort(final Map<ChronoIdentifier, Pair<Object, Object>> identifierToValue) { checkNotNull(identifierToValue, "Precondition violation - argument 'identifierToValue' must not be NULL!"); List<Pair<ChronoIdentifier, Pair<Object, Object>>> resultList = Lists.newArrayList(); for (Entry<ChronoIdentifier, Pair<Object, Object>> entry : identifierToValue.entrySet()) { resultList.add(Pair.of(entry.getKey(), entry.getValue())); } Collections.sort(resultList, new WorkloadComparator()); return resultList; } private static class WorkloadComparator implements Comparator<Pair<ChronoIdentifier, Pair<Object, Object>>> { @Override public int compare(final Pair<ChronoIdentifier, Pair<Object, Object>> o1, final Pair<ChronoIdentifier, Pair<Object, Object>> o2) { if (o1 == null && o2 == null) { return 0; } else if (o1 != null && o2 == null) { return 1; } else if (o1 == null && o2 != null) { return -1; } ChronoIdentifier key1 = o1.getKey(); ChronoIdentifier key2 = o2.getKey(); // order by timestamp int timestampCompare = Long.compare(key1.getTimestamp(), key2.getTimestamp()); if (timestampCompare != 0) { return timestampCompare; } // then order by branch int branchCompare = key1.getBranchName().compareTo(key2.getBranchName()); if (branchCompare != 0) { return branchCompare; } // then order by keyspace int keyspaceCompare = key1.getKeyspace().compareTo(key2.getKeyspace()); if (keyspaceCompare != 0) { return keyspaceCompare; } // in all other cases, order by key return key1.getKey().compareTo(key2.getKey()); } } }
2,107
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoIndexDocumentModificationsImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/index/ChronoIndexDocumentModificationsImpl.java
package org.chronos.chronodb.internal.impl.index; import static com.google.common.base.Preconditions.*; import java.util.Collections; import java.util.Set; import org.chronos.chronodb.internal.api.index.ChronoIndexDocumentModifications; import org.chronos.chronodb.internal.api.index.DocumentAddition; import org.chronos.chronodb.internal.api.index.DocumentDeletion; import org.chronos.chronodb.internal.api.index.DocumentValidityTermination; import com.google.common.collect.Sets; public class ChronoIndexDocumentModificationsImpl implements ChronoIndexDocumentModifications { private final Set<DocumentValidityTermination> documentValidityTerminations; private final Set<DocumentAddition> documentCreations; private final Set<DocumentDeletion> documentDeletions; public ChronoIndexDocumentModificationsImpl() { this.documentValidityTerminations = Sets.newHashSet(); this.documentCreations = Sets.newHashSet(); this.documentDeletions = Sets.newHashSet(); } @Override public void addDocumentValidityTermination(final DocumentValidityTermination termination) { checkNotNull(termination, "Precondition violation - argument 'termination' must not be NULL!"); this.documentValidityTerminations.add(termination); } @Override public Set<DocumentValidityTermination> getDocumentValidityTerminations() { return Collections.unmodifiableSet(this.documentValidityTerminations); } @Override public void addDocumentCreation(final DocumentAddition creation) { checkNotNull(creation, "Precondition violation - argument 'creation' must not be NULL!"); this.documentCreations.add(creation); } @Override public Set<DocumentAddition> getDocumentCreations() { return Collections.unmodifiableSet(this.documentCreations); } @Override public void addDocumentDeletion(final DocumentDeletion deletion) { checkNotNull(deletion, "Precondition violation - argument 'deletion' must not be NULL!"); this.documentDeletions.add(deletion); } @Override public Set<DocumentDeletion> getDocumentDeletions() { return Collections.unmodifiableSet(this.documentDeletions); } @Override public boolean isEmpty() { return this.documentCreations.isEmpty() && this.documentValidityTerminations.isEmpty() && this.documentDeletions.isEmpty(); } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("IndexModifications["); String separator = ""; for (DocumentAddition creation : this.documentCreations) { builder.append(separator); separator = ", "; builder.append(creation.toString()); } for (DocumentValidityTermination termination : this.documentValidityTerminations) { builder.append(separator); separator = ", "; builder.append(termination.toString()); } for (DocumentDeletion deletion : this.documentDeletions) { builder.append(separator); separator = ", "; builder.append(deletion.toString()); } builder.append("]"); return builder.toString(); } }
2,971
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
DocumentValidityTerminationImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/index/DocumentValidityTerminationImpl.java
package org.chronos.chronodb.internal.impl.index; import static com.google.common.base.Preconditions.*; import org.chronos.chronodb.internal.api.index.ChronoIndexDocument; import org.chronos.chronodb.internal.api.index.DocumentValidityTermination; public class DocumentValidityTerminationImpl implements DocumentValidityTermination { private final ChronoIndexDocument document; private final long terminationTimestamp; public DocumentValidityTerminationImpl(final ChronoIndexDocument document, final long terminationTimestamp) { checkNotNull(document, "Precondition violation - argument 'document' must not be NULL!"); checkArgument(terminationTimestamp >= 0, "Precondition violation - argument 'terminationTimestamp' must not be negative!"); this.document = document; this.terminationTimestamp = terminationTimestamp; } @Override public ChronoIndexDocument getDocument() { return this.document; } @Override public long getTerminationTimestamp() { return this.terminationTimestamp; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("TERMINATE("); builder.append(this.document.getIndex()); builder.append("->"); builder.append(this.document.getKeyspace()); builder.append("->"); builder.append(this.document.getKey()); builder.append("->"); builder.append(this.document.getIndexedValue()); builder.append("@"); builder.append(this.terminationTimestamp); builder.append(")"); return builder.toString(); } }
1,514
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
DocumentAdditionImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/index/DocumentAdditionImpl.java
package org.chronos.chronodb.internal.impl.index; import static com.google.common.base.Preconditions.*; import org.chronos.chronodb.api.SecondaryIndex; import org.chronos.chronodb.api.key.ChronoIdentifier; import org.chronos.chronodb.internal.api.Period; import org.chronos.chronodb.internal.api.index.ChronoIndexDocument; import org.chronos.chronodb.internal.api.index.DocumentAddition; public class DocumentAdditionImpl implements DocumentAddition { private final ChronoIndexDocument document; public DocumentAdditionImpl(final ChronoIdentifier identifier, final SecondaryIndex index, final Object indexValue) { this(new ChronoIndexDocumentImpl(identifier, index, indexValue)); } public DocumentAdditionImpl(final ChronoIndexDocument document) { checkNotNull(document, "Precondition violation - argument 'document' must not be NULL!"); this.document = document; } @Override public ChronoIndexDocument getDocumentToAdd() { return this.document; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("ADD("); builder.append(this.document.getIndex()); builder.append("->"); builder.append(this.document.getBranch()); builder.append("->"); builder.append(this.document.getKeyspace()); builder.append("->"); builder.append(this.document.getKey()); builder.append(", value='"); builder.append(this.document.getIndexedValue()); builder.append("' ("); builder.append(this.document.getIndexedValue().getClass().getName()); builder.append("), "); builder.append(Period.createRange(this.document.getValidFromTimestamp(), this.document.getValidToTimestamp())); builder.append(")"); return builder.toString(); } }
1,710
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoIndexDocumentImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/index/ChronoIndexDocumentImpl.java
package org.chronos.chronodb.internal.impl.index; import static com.google.common.base.Preconditions.*; import java.util.UUID; import org.chronos.chronodb.api.SecondaryIndex; import org.chronos.chronodb.api.key.ChronoIdentifier; import org.chronos.chronodb.internal.api.index.ChronoIndexDocument; public class ChronoIndexDocumentImpl implements ChronoIndexDocument { // ================================================================================================================= // FIELDS // ================================================================================================================= private final String documentId; private final String branch; private final SecondaryIndex index; private final String keyspace; private final String key; private final Object indexedValue; private final long validFrom; private long validTo; // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= public ChronoIndexDocumentImpl(final ChronoIdentifier identifier, final SecondaryIndex index, final Object indexValue) { this(index, identifier.getBranchName(), identifier.getKeyspace(), identifier.getKey(), indexValue, identifier.getTimestamp()); } public ChronoIndexDocumentImpl(final SecondaryIndex index, final String branchName, final String keyspace, final String key, final Object indexedValue, final long validFrom) { this(UUID.randomUUID().toString(), index, branchName, keyspace, key, indexedValue, validFrom, Long.MAX_VALUE); } public ChronoIndexDocumentImpl(final String id, final SecondaryIndex index, final String branchName, final String keyspace, final String key, final Object indexedValue, final long validFrom, final long validTo) { checkNotNull(id, "Precondition violation - argument 'id' must not be NULL!"); checkNotNull(index, "Precondition violation - argument 'index' must not be NULL!"); checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!"); checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); checkNotNull(indexedValue, "Precondition violation - argument 'indexedValue' must not be NULL!"); checkArgument(validFrom >= 0, "Precondition violation - argument 'validFrom' must be >= 0 (value: " + validFrom + ")!"); checkArgument(validTo >= 0, "Precondition violation - argument 'validTo' must be >= 0 (value: " + validTo + ")!"); checkArgument(validFrom < validTo, "Precondition violation - argument 'validTo' must be > 'validFrom'!"); this.documentId = id; this.index = index; this.branch = branchName; this.keyspace = keyspace; this.key = key; this.indexedValue = indexedValue; this.validFrom = validFrom; this.validTo = validTo; } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public String getDocumentId() { return this.documentId; } @Override public SecondaryIndex getIndex() { return this.index; } @Override public String getBranch() { return this.branch; } @Override public String getKeyspace() { return this.keyspace; } @Override public String getKey() { return this.key; } @Override public Object getIndexedValue() { return this.indexedValue; } @Override public long getValidFromTimestamp() { return this.validFrom; } @Override public long getValidToTimestamp() { return this.validTo; } @Override public void setValidToTimestamp(final long validTo) { checkArgument(validTo > this.validFrom, "Precondition violation - argument 'validTo' must be > 'validFrom'!"); this.validTo = validTo; } // ================================================================================================================= // HASH CODE & EQUALS // ================================================================================================================= @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.documentId == null ? 0 : this.documentId.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } ChronoIndexDocumentImpl other = (ChronoIndexDocumentImpl) obj; if (this.documentId == null) { if (other.documentId != null) { return false; } } else if (!this.documentId.equals(other.documentId)) { return false; } return true; } // ================================================================================================================= // TO STRING // ================================================================================================================= @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("IndexDoc['"); builder.append(this.getIndex()); builder.append("'->'"); builder.append(this.getKeyspace()); builder.append("'->'"); builder.append(this.getKey()); builder.append("' = '"); builder.append(this.getIndexedValue()); builder.append("', ["); builder.append(this.getValidFromTimestamp()); builder.append(";"); if (this.validTo >= Long.MAX_VALUE) { builder.append("MAX"); } else { builder.append(this.getValidToTimestamp()); } builder.append("]"); return builder.toString(); } }
5,824
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
IndexValueDiff.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/index/diff/IndexValueDiff.java
package org.chronos.chronodb.internal.impl.index.diff; import org.chronos.chronodb.api.SecondaryIndex; import java.util.Set; public interface IndexValueDiff { /** * Returns the "old" (previous) value, i.e. the "left" side of the diff. * * <p> * If the {@linkplain #getOldValue() old value} is <code>null</code> and the {@linkplain #getNewValue() new value} is non-<code>null</code>, then this diff represents an {@linkplain #isEntryAddition() entry addition}. * * @return The old value. May be <code>null</code>. */ public Object getOldValue(); /** * Returns the "new" (next) value, i.e. the "right" side of the diff. * * <p> * If the {@linkplain #getOldValue() old value} is <code>null</code> and the {@linkplain #getNewValue() new value} is non-<code>null</code>, then this diff represents an {@linkplain #isEntryAddition() entry addition}. * * @return The new value. May be <code>null</code>. */ public Object getNewValue(); /** * Returns the value additions for the given index name. * * @param indexName * The index name to get the additions for. Must not be <code>null</code>. * * @return The value additions. Never <code>null</code>. May be empty if nothing was added to the given index. */ public Set<Object> getAdditions(final SecondaryIndex index); /** * Returns the value removals for the given index name. * * @param indexName * The index name to get the removals for. Must not be <code>null</code>. * * @return The value removals. Never <code>null</code>. May be empty if nothing was removed from the given index. */ public Set<Object> getRemovals(final SecondaryIndex index); /** * Returns the set of indices that have actual changes in this diff. * * <p> * This is equivalent to the set of indices where the set of {@linkplain #getAdditions(SecondaryIndex) additions} and/or the set of {@linkplain #getRemovals(SecondaryIndex) removals} is non-empty. * * @return The set of names of changed indices. May be empty if this diff {@linkplain #isEmpty() is empty}, but never <code>null</code>. */ public Set<SecondaryIndex> getChangedIndices(); /** * Checks if there are changes in this diff for the index with the given name. * * @param indexName * The name of the index to check for changes. Must not be <code>null</code>. * * @return <code>true</code> if there are changes to the index with the given name, otherwise <code>false</code>. */ public boolean isIndexChanged(final SecondaryIndex index); /** * Checks if this diff is empty, i.e. does not contain any changes. * * <p> * If this method returns <code>true</code>, then {@link #getChangedIndices()} all of the following methods will return the empty set: * <ul> * <li>{@link #getChangedIndices()} * <li>{@link #getAdditions(SecondaryIndex)} (for every non-<code>null</code> argument string) * <li>{@link #getRemovals(SecondaryIndex)} (for every non-<code>null</code> argument string) * </ul> * * <p> * Please note that any given diff can either be {@linkplain #isAdditive() additive}, {@linkplain #isSubtractive() subtractive}, {@linkplain #isMixed() mixed} or {@linkplain #isEmpty() empty}. Every diff will return <code>true</code> for exactly one of these states. * * @return <code>true</code> if this is an empty diff, otherwise <code>false</code>. */ public boolean isEmpty(); /** * Checks if this diff represents an entry addition, i.e. the {@linkplain #getOldValue() old value} is <code>null</code> and the {@linkplain #getNewValue() new value} is non-<code>null</code>. * * <p> * Please note that {@link #isEntryAddition()} and {@link #isEntryRemoval()} will both return <code>false</code> if both the {@linkplain #getOldValue() old value} and the {@linkplain #getNewValue() new value} are <code>null</code>. In any other case, either {@link #isEntryAddition()} or {@link #isEntryRemoval()} will return <code>true</code>, but never both of them. * * @return <code>true</code> if this diff represents an entry addition, otherwise <code>false</code>. */ public default boolean isEntryAddition() { return this.getOldValue() == null && this.getNewValue() != null; } /** * Checks if this diff represents an entry removal, i.e. the {@linkplain #getOldValue() old value} is non- <code>null</code> and the {@linkplain #getNewValue() new value} is <code>null</code>. * * <p> * Please note that {@link #isEntryAddition()} and {@link #isEntryRemoval()} will both return <code>false</code> if both the {@linkplain #getOldValue() old value} and the {@linkplain #getNewValue() new value} are <code>null</code>. In any other case, either {@link #isEntryAddition()} or {@link #isEntryRemoval()} will return <code>true</code>, but never both of them. * * @return <code>true</code> if this diff represents an entry removal, otherwise <code>false</code>. */ public default boolean isEntryRemoval() { return this.getOldValue() != null && this.getNewValue() == null; } /** * Checks if this diff represents an entry update, i.e. the {@linkplain #getOldValue() old value} is non- <code>null</code> and the {@linkplain #getNewValue() new value} is non-<code>null</code>. * * @return <code>true</code> if this diff represents an entry update, otherwise <code>false</code>. */ public default boolean isEntryUpdate() { return this.getOldValue() != null && this.getNewValue() != null; } /** * Checks if all changes in this diff are additive (contains only additions, but no removals). * * <p> * In other words, this method will return <code>true</code> if and only if all of the following conditions hold: * <ul> * <li>{@link #getChangedIndices()} returns a non-empty set * <li>{@link #getAdditions(SecondaryIndex)} will return a non-empty set for at least one index name * <li>{@link #getRemovals(SecondaryIndex)} will return the empty set, for all index names * </ul> * * <p> * Please note that any given diff can either be {@linkplain #isAdditive() additive}, {@linkplain #isSubtractive() subtractive}, {@linkplain #isMixed() mixed} or {@linkplain #isEmpty() empty}. Every diff will return <code>true</code> for exactly one of these states. * * @return <code>true</code> if this diff is additive, otherwise <code>false</code>. * * @see #isSubtractive() * @see #isMixed() * @see #isEmpty() */ public boolean isAdditive(); /** * Checks if all changes in this diff are subtractive (contains only removals, but no additions). * * <p> * In other words, this method will return <code>true</code> if and only if all of the following conditions hold: * <ul> * <li>{@link #getChangedIndices()} returns a non-empty set * <li>{@link #getAdditions(SecondaryIndex)} will return the empty set, for all index names * <li>{@link #getRemovals(SecondaryIndex)} will return a non-empty set for at least one index name * </ul> * * <p> * Please note that any given diff can either be {@linkplain #isAdditive() additive}, {@linkplain #isSubtractive() subtractive}, {@linkplain #isMixed() mixed} or {@linkplain #isEmpty() empty}. Every diff will return <code>true</code> for exactly one of these states. * * @return <code>true</code> if this diff is subtractive, otherwise <code>false</code>. * * @see #isAdditive() * @see #isMixed() * @see #isEmpty() */ public boolean isSubtractive(); /** * Checks if the changes in this diff are mixed (contains additions as well as removals). * * <p> * In other words, this method will return <code>true</code> if and only if all of the following conditions hold: * <ul> * <li>{@link #getChangedIndices()} returns a non-empty set * <li>{@link #getAdditions(SecondaryIndex)} will return a non-empty set for at least one index name * <li>{@link #getRemovals(SecondaryIndex)} will return a non-empty set for at least one index name * </ul> * * <p> * Please note that any given diff can either be {@linkplain #isAdditive() additive}, {@linkplain #isSubtractive() subtractive}, {@linkplain #isMixed() mixed} or {@linkplain #isEmpty() empty}. Every diff will return <code>true</code> for exactly one of these states. * * @return <code>true</code> if this diff is mixed, otherwise <code>false</code>. * * @see #isAdditive() * @see #isSubtractive() * @see #isEmpty() */ public boolean isMixed(); }
8,405
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
MutableIndexValueDiff.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/index/diff/MutableIndexValueDiff.java
package org.chronos.chronodb.internal.impl.index.diff; import static com.google.common.base.Preconditions.*; import java.util.Collections; import java.util.Set; import com.google.common.collect.HashMultimap; import com.google.common.collect.SetMultimap; import com.google.common.collect.Sets; import org.chronos.chronodb.api.SecondaryIndex; public class MutableIndexValueDiff implements IndexValueDiff { private final Object oldValue; private final Object newValue; private SetMultimap<SecondaryIndex, Object> indexToAdditions; private SetMultimap<SecondaryIndex, Object> indexToRemovals; public MutableIndexValueDiff(final Object oldValue, final Object newValue) { this.oldValue = oldValue; this.newValue = newValue; } @Override public Object getOldValue() { return this.oldValue; } @Override public Object getNewValue() { return this.newValue; } @Override public Set<Object> getAdditions(final SecondaryIndex index) { if (this.indexToAdditions == null || this.indexToAdditions.isEmpty()) { return Collections.emptySet(); } return Collections.unmodifiableSet(this.indexToAdditions.get(index)); } @Override public Set<Object> getRemovals(final SecondaryIndex indexName) { if (this.indexToRemovals == null || this.indexToRemovals.isEmpty()) { return Collections.emptySet(); } return Collections.unmodifiableSet(this.indexToRemovals.get(indexName)); } @Override public Set<SecondaryIndex> getChangedIndices() { if (this.isEmpty()) { return Collections.emptySet(); } if (this.indexToAdditions == null || this.indexToAdditions.isEmpty()) { return Collections.unmodifiableSet(this.indexToRemovals.keySet()); } if (this.indexToRemovals == null || this.indexToRemovals.isEmpty()) { return Collections.unmodifiableSet(this.indexToAdditions.keySet()); } Set<SecondaryIndex> changedIndices = Sets.union(this.indexToAdditions.keySet(), this.indexToRemovals.keySet()); return Collections.unmodifiableSet(changedIndices); } @Override public boolean isEmpty() { // both change sets are either NULL (never touched) or empty (touched and then cleared) if ((this.indexToAdditions == null || this.indexToAdditions.isEmpty()) && (this.indexToRemovals == null || this.indexToRemovals.isEmpty())) { return true; } else { return false; } } @Override public boolean isAdditive() { if (this.indexToAdditions != null && this.indexToAdditions.size() > 0) { if (this.indexToRemovals == null || this.indexToRemovals.isEmpty()) { return true; } } return false; } @Override public boolean isSubtractive() { if (this.indexToRemovals != null && this.indexToRemovals.size() > 0) { if (this.indexToAdditions == null || this.indexToAdditions.isEmpty()) { return true; } } return false; } @Override public boolean isMixed() { if (this.indexToAdditions != null && this.indexToAdditions.size() > 0) { if (this.indexToRemovals != null && this.indexToRemovals.size() > 0) { return true; } } return false; } @Override public boolean isIndexChanged(final SecondaryIndex index) { if (this.indexToAdditions != null && this.indexToAdditions.containsKey(index)) { return true; } else if (this.indexToRemovals != null && this.indexToRemovals.containsKey(index)) { return true; } return false; } public void add(final SecondaryIndex index, final Object value) { checkNotNull(index, "Precondition violation - argument 'index' must not be NULL!"); checkNotNull(value, "Precondition violation - argument 'value' must not be NULL!"); if (this.isEntryRemoval()) { throw new IllegalStateException( "Cannot insert additive diff values to a diff that represents an entry removal!"); } if (this.indexToAdditions == null) { this.indexToAdditions = HashMultimap.create(); } this.indexToAdditions.put(index, value); if (this.indexToRemovals != null) { this.indexToRemovals.remove(index, value); } } public void removeSingleValue(final SecondaryIndex index, final Object value) { checkNotNull(index, "Precondition violation - argument 'index' must not be NULL!"); checkNotNull(value, "Precondition violation - argument 'value' must not be NULL!"); if (this.isEntryAddition()) { throw new IllegalStateException( "Cannot insert subtractive diff values to a diff that represents an entry addition!"); } if (this.indexToRemovals == null) { this.indexToRemovals = HashMultimap.create(); } this.indexToRemovals.put(index, value); if (this.indexToAdditions != null) { this.indexToAdditions.remove(index, value); } } public void removeMultipleValues(final SecondaryIndex index, final Set<Object> values) { checkNotNull(index, "Precondition violation - argument 'index' must not be NULL!"); if (values == null || values.isEmpty()) { return; } for (Object value : values) { this.removeSingleValue(index, value); } } }
4,921
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
IndexingUtils.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/index/diff/IndexingUtils.java
package org.chronos.chronodb.internal.impl.index.diff; import com.google.common.collect.HashMultimap; import com.google.common.collect.SetMultimap; import com.google.common.collect.Sets; import org.chronos.chronodb.api.SecondaryIndex; import java.util.Set; import static com.google.common.base.Preconditions.*; public class IndexingUtils { public static void assertIsValidIndexName(String indexName) { checkNotNull(indexName, "Precondition violation - argument 'indexName' must not be NULL!"); if (indexName.isEmpty()) { throw new IllegalArgumentException("The given 'indexName' is blank!"); } String trimmed = indexName.trim(); if (trimmed.equals(indexName) == false) { throw new IllegalArgumentException("The given 'indexName' starts or ends with whitespace, which is not allowed!"); } if(indexName.contains("\n")){ throw new IllegalArgumentException("The given 'indexName' contains line breaks / newlines, which are not allowed!"); } if(indexName.length() > 255){ throw new IllegalArgumentException("The given 'indexName' is too long (maximum allowed is 255 characters, your index name contains " + indexName.length() + " characters)."); } } /** * Calculates a diff between the indexed values of the given <code>oldValue</code> and <code>newValue</code>. * * @param indices A mapping from index names to indexers. This method will attempt to resolve the index value(s) for all * index names. May be empty, in which case the resulting diff will also be empty. Must not be * <code>null</code>. * @param oldValue The old (previous) value object to analyze. May be <code>null</code> to indicate that the * <code>newValue</code> is an addition. * @param newValue The new value object to analyze. May be <code>null</code> to indicate that the <code>oldValue</code> * was deleted. * @return The diff between the old and new index values. Never <code>null</code>, may be empty. */ public static IndexValueDiff calculateDiff(final Set<SecondaryIndex> indices, final Object oldValue, final Object newValue) { checkNotNull(indices, "Precondition violation - argument 'indices' must not be NULL!"); MutableIndexValueDiff diff = new MutableIndexValueDiff(oldValue, newValue); if (indices.isEmpty() || oldValue == null && newValue == null) { // return the empty diff return diff; } // iterate over the known indices for (SecondaryIndex index : indices) { // prepare the sets of values for that index Set<Comparable<?>> oldValues = index.getIndexedValuesForObject(oldValue); Set<Comparable<?>> newValues = index.getIndexedValuesForObject(newValue); // calculate the set differences Set<Object> addedValues = Sets.newHashSet(); addedValues.addAll(newValues); addedValues.removeAll(oldValues); Set<Object> removedValues = Sets.newHashSet(); removedValues.addAll(oldValues); removedValues.removeAll(newValues); // update the diff for (Object addedValue : addedValues) { diff.add(index, addedValue); } diff.removeMultipleValues(index, removedValues); } return diff; } /** * Returns the indexed values for the given object. * * @param indices A multimap from index name to indexers. Must not be <code>null</code>, may be empty, in which case the * resulting multimap will be empty. * @param object The object to get the index values for. May be <code>null</code>, in which case the resulting multimap * will be empty. * @return The mapping from index name to indexed values. May be empty, but never <code>null</code>. */ public static SetMultimap<SecondaryIndex, Object> getIndexedValuesForObject( final Set<SecondaryIndex> indices, final Object object) { checkNotNull(indices, "Precondition violation - argument 'indices' must not be NULL!"); SetMultimap<SecondaryIndex, Object> indexValuesMap = HashMultimap.create(); if (object == null || indices.isEmpty()) { return indexValuesMap; } for (SecondaryIndex index : indices) { Set<Comparable<?>> indexValues = index.getIndexedValuesForObject(object); if (indexValues.isEmpty()) { continue; } indexValuesMap.putAll(index, indexValues); } return indexValuesMap; } public static boolean isValidIndexValue(final Object obj) { if (obj == null) { return false; } if (obj instanceof String) { String s = (String) obj; if (s.trim().isEmpty()) { return false; } } return true; } }
5,136
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
SetView.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/index/setview/SetView.java
package org.chronos.chronodb.internal.impl.index.setview; import com.google.common.collect.Sets; import java.util.Set; public interface SetView<T> extends Set<T> { // ================================================================================================================= // STATIC HELPERS // ================================================================================================================= public static int estimateSizeOf(Set<?> set){ if(set instanceof SetView){ return ((SetView<?>)set).estimatedSize(); }else{ return set.size(); } } // ================================================================================================================= // STATIC FACTORIES // ================================================================================================================= public static <T> SetView<T> intersection(Set<T> a, Set<T> b){ int sizeLeft = estimateSizeOf(a); int sizeRight = estimateSizeOf(b); Set<T> data; if (sizeLeft < sizeRight) { data = Sets.intersection(a, b); } else { data = Sets.intersection(b, a); } // pessimistic: the minimum size of the result of a // set intersection is the empty set. int sizeMin = 0; // fact: the maximum size of the result of a // set intersection is the minimum of the two sizes // of the origin sets (a set cannot grow larger by // intersecting it with another set) int sizeMax = Math.min(sizeLeft, sizeRight); return new SetViewImpl<>(data, sizeMin, sizeMax); } public static <T> SetView<T> union(Set<T> a, Set<T> b){ int sizeLeft = estimateSizeOf(a); int sizeRight = estimateSizeOf(b); Set<T> data = Sets.union(a, b); // the minimum size of a set union is the size of the // larger of the two input sets. This is the case if // one set entirely contains the other. int sizeMin = Math.max(sizeLeft, sizeRight); // the maximum size of a set union is the sum of the // two input set sizes. This is the case if the sets // are disjoint (contain no common element). int sizeMax = sizeLeft + sizeRight; return new SetViewImpl<>(data, sizeMin, sizeMax); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= public int maxSize(); public int minSize(); public default int estimatedSize(){ return (maxSize() + minSize()) / 2; } }
2,799
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
SetViewImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/index/setview/SetViewImpl.java
package org.chronos.chronodb.internal.impl.index.setview; import com.google.common.collect.Sets; import java.util.AbstractSet; import java.util.Collection; import java.util.Iterator; import java.util.Set; public class SetViewImpl<T> extends AbstractSet<T> implements SetView<T> { // ================================================================================================================= // FIELDS // ================================================================================================================= private final Set<T> data; private final int sizeMin; private final int sizeMax; // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= protected SetViewImpl(Set<T> data, int sizeMin, int sizeMax) { this.data = data; this.sizeMin = sizeMin; this.sizeMax = sizeMax; } // ================================================================================================================= // PUBLIC API // ================================================================================================================= public int maxSize() { return sizeMax; } public int minSize() { return sizeMin; } @Override public int size() { return data.size(); } @Override public boolean isEmpty() { return data.isEmpty(); } @Override public boolean contains(final Object o) { return data.contains(o); } @Override public Iterator<T> iterator() { return data.iterator(); } @Override public Object[] toArray() { return data.toArray(); } @Override public <T1> T1[] toArray(final T1[] a) { return data.toArray(a); } @Override public boolean add(final T t) { throw new UnsupportedOperationException(); } @Override public boolean remove(final Object o) { throw new UnsupportedOperationException(); } @Override public boolean containsAll(final Collection<?> c) { return this.data.containsAll(c); } @Override public boolean addAll(final Collection<? extends T> c) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(final Collection<?> c) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(final Collection<?> c) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } }
2,794
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoIndexQueryCache.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/index/querycache/ChronoIndexQueryCache.java
package org.chronos.chronodb.internal.impl.index.querycache; import java.util.Set; import java.util.concurrent.Callable; import org.chronos.chronodb.api.Branch; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.internal.api.query.searchspec.SearchSpecification; import com.google.common.cache.CacheStats; /** * The {@link ChronoIndexQueryCache} is used to cache the results of index queries in a {@link ChronoDB} instance. * * <p> * This cache is essentially just a mapping from <i>executed query</i> to <i>query result</i>. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public interface ChronoIndexQueryCache { /** * Runs the given search through the cache. * * <p> * If the result for the requested search is already cached, the cached result will be returned. Otherwise, the result will be calculated via the given <code>loadingFunction</code>, and automatically be cached before returning it. * * @param timestamp * The timestamp at which to execute the query. Must not be negative. * @param branch * The branch to run the index query on. Must not be <code>null</code>. * @param searchSpec * The search specification to fulfill. Must not be <code>null</code>. * @param keyspace * The keyspace to search in. Must not be <code>null</code>. * @param loadingFunction * The function to use in case that the cache doesn't contain the result of the given query. * * @return The keys resulting from the given search request. May be empty, but never <code>null</code>. */ public Set<String> getOrCalculate(final long timestamp, final Branch branch, String keyspace, final SearchSpecification<?,?> searchSpec, final Callable<Set<String>> loadingFunction); /** * Returns the statistics of this cache. * * <p> * The statistics object is only available when the <code>recordStatistics</code> parameter of the constructor was set to <code>true</code>. * * @return The statistics, or <code>null</code> if recording is turned off. */ public CacheStats getStats(); /** * Clears this query cache. */ public void clear(); }
2,228
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
LRUIndexQueryCache.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/index/querycache/LRUIndexQueryCache.java
package org.chronos.chronodb.internal.impl.index.querycache; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import org.chronos.chronodb.api.Branch; import org.chronos.chronodb.internal.api.query.searchspec.SearchSpecification; import org.chronos.chronodb.internal.util.Quadruple; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheStats; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A simple query cache on a least-recently-used basis. * * <p> * Query results are keyed against a timestamp and a {@link SearchSpecification}. Note that this simple cache does not support sharing query results across many timestamps. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public class LRUIndexQueryCache implements ChronoIndexQueryCache { private static final Logger log = LoggerFactory.getLogger(LRUIndexQueryCache.class); private final Cache<Quadruple<Long, Branch, String, SearchSpecification<?,?>>, Set<String>> cache; public LRUIndexQueryCache(final int maxSize, final boolean recordStatistics) { CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder().maximumSize(maxSize); if (recordStatistics) { builder = builder.recordStats(); } this.cache = builder.build(); } @Override public Set<String> getOrCalculate(final long timestamp, final Branch branch, final String keyspace, final SearchSpecification<?,?> searchSpec, final Callable<Set<String>> loadingFunction) { try { Set<String> result = this.cache.get(Quadruple.of(timestamp, branch, keyspace, searchSpec), loadingFunction); return result; } catch (ExecutionException e) { log.error("Failed to load result of '" + searchSpec + "' at timestamp " + timestamp + "!", e); return null; } } @Override public CacheStats getStats() { return this.cache.stats(); } @Override public void clear() { this.cache.invalidateAll(); } }
2,024
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
NoIndexQueryCache.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/index/querycache/NoIndexQueryCache.java
package org.chronos.chronodb.internal.impl.index.querycache; import java.util.Set; import java.util.concurrent.Callable; import org.chronos.chronodb.api.Branch; import org.chronos.chronodb.api.exceptions.ChronoDBIndexingException; import org.chronos.chronodb.internal.api.query.searchspec.SearchSpecification; import com.google.common.cache.CacheStats; /** * This implementation of {@link ChronoIndexQueryCache} "fakes" a cache. * * <p> * The only purpose of this class is to act as a placeholder for the cache object when caching is disabled. It does nothing else than passing the given search specification to the loading function. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public class NoIndexQueryCache implements ChronoIndexQueryCache { @Override public Set<String> getOrCalculate(final long timestamp, final Branch branch, final String keyspace, final SearchSpecification<?,?> searchSpec, final Callable<Set<String>> loadingFunction) { try { return loadingFunction.call(); } catch (Exception e) { throw new ChronoDBIndexingException("Failed to perform index query!", e); } } @Override public CacheStats getStats() { return null; } @Override public void clear() { // nothing to do } }
1,267
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoDBBackendProviderService.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/base/builder/database/service/ChronoDBBackendProviderService.java
package org.chronos.chronodb.internal.impl.base.builder.database.service; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import org.chronos.chronodb.api.builder.database.spi.ChronoDBBackendProvider; import org.chronos.chronodb.api.exceptions.ChronoDBConfigurationException; import java.util.Collections; import java.util.Iterator; import java.util.ServiceConfigurationError; import java.util.ServiceLoader; import java.util.Set; import static com.google.common.base.Preconditions.*; public class ChronoDBBackendProviderService { // ================================================================================================================= // SINGLETON // ================================================================================================================= private static final ChronoDBBackendProviderService INSTANCE = new ChronoDBBackendProviderService(); public static ChronoDBBackendProviderService getInstance() { return INSTANCE; } private ChronoDBBackendProviderService() { // private; use the static instance } // ================================================================================================================= // FIELDS // ================================================================================================================= private final ServiceLoader<ChronoDBBackendProvider> loader = ServiceLoader.load(ChronoDBBackendProvider.class); // ================================================================================================================= // PUBLIC API // ================================================================================================================= public ChronoDBBackendProvider getBackendProvider(String chronosBackend) { checkNotNull(chronosBackend, "Precondition violation - argument 'chronosBackend' must not be NULL!"); try { Iterator<ChronoDBBackendProvider> iterator = this.loader.iterator(); Set<ChronoDBBackendProvider> matchingProviders = Sets.newHashSet(); while (iterator.hasNext()) { ChronoDBBackendProvider provider = iterator.next(); if (provider.matchesBackendName(chronosBackend)) { matchingProviders.add(provider); } } if (matchingProviders.isEmpty()) { throw new ChronoDBConfigurationException("No ChronoDB Implementation on the classpath matched the backend '" + chronosBackend + "'! Are you missing a dependency?"); } else if (matchingProviders.size() > 1) { throw new ChronoDBConfigurationException("Multiple ChronoDB Implementations on the classpath matched the backend '" + chronosBackend + "'! Please remove duplicate implementations from your classpath."); } return Iterables.getOnlyElement(matchingProviders); } catch (ServiceConfigurationError e) { throw new ChronoDBConfigurationException("An error occurred when trying to detect ChronoDB Implementations on the classpath! See root cause for details.", e); } } public Set<ChronoDBBackendProvider> getAvailableBuilders() { Set<ChronoDBBackendProvider> resultSet = Sets.newHashSet(); Iterables.addAll(resultSet, this.loader); return Collections.unmodifiableSet(resultSet); } }
3,456
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AtomicConflictImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/conflict/AtomicConflictImpl.java
package org.chronos.chronodb.internal.impl.conflict; import static com.google.common.base.Preconditions.*; import org.apache.commons.lang3.tuple.Pair; import org.chronos.chronodb.api.conflict.AtomicConflict; import org.chronos.chronodb.api.key.ChronoIdentifier; public class AtomicConflictImpl implements AtomicConflict { private final long transactionTimestamp; private final ChronoIdentifier sourceKey; private final Object sourceValue; private final ChronoIdentifier targetKey; private final Object targetValue; private final AncestorFetcher ancestorFetcher; private boolean commonAncestorLoaded = false; private ChronoIdentifier commonAncestorKey; private Object commonAncestorValue; public AtomicConflictImpl(final long transactionTimestamp, final ChronoIdentifier sourceKey, final Object sourceValue, final ChronoIdentifier targetKey, final Object targetValue, final AncestorFetcher ancestorFetcher) { checkArgument(transactionTimestamp >= 0, "Precondition violation - argument 'transactionTimestamp' must not be negative!"); checkNotNull(sourceKey, "Precondition violation - argument 'sourceKey' must not be NULL!"); checkNotNull(targetKey, "Precondition violation - argument 'targetKey' must not be NULL!"); checkArgument(sourceKey.getKeyspace().equals(targetKey.getKeyspace()), "Precondition violation - arguments 'sourceKey' and 'targetKey' must specify the same keyspaces!"); checkArgument(sourceKey.getKey().equals(targetKey.getKey()), "Precondition violation - arguments 'sourceKey' and 'targetKey' must specify the same keys!"); checkNotNull(ancestorFetcher, "Precondition violation - argument 'ancestorFetcher' must not be NULL!"); this.transactionTimestamp = transactionTimestamp; this.sourceKey = sourceKey; this.sourceValue = sourceValue; this.targetKey = targetKey; this.targetValue = targetValue; this.ancestorFetcher = ancestorFetcher; } @Override public ChronoIdentifier getSourceKey() { return this.sourceKey; } @Override public Object getSourceValue() { return this.sourceValue; } @Override public ChronoIdentifier getTargetKey() { return this.targetKey; } @Override public Object getTargetValue() { return this.targetValue; } @Override public ChronoIdentifier getCommonAncestorKey() { this.assertCommonAncestorIsLoaded(); return this.commonAncestorKey; } @Override public Object getCommonAncestorValue() { this.assertCommonAncestorIsLoaded(); return this.commonAncestorValue; } @Override public long getTransactionTimestamp() { return this.transactionTimestamp; } private void assertCommonAncestorIsLoaded() { if (this.commonAncestorLoaded) { return; } Pair<ChronoIdentifier, Object> ancestor = this.ancestorFetcher.findCommonAncestor(this.transactionTimestamp, this.getSourceKey(), this.getTargetKey()); if (ancestor == null) { // there is no common ancestor (can this even happen?) this.commonAncestorKey = null; this.commonAncestorValue = null; } else { this.commonAncestorKey = ancestor.getKey(); this.commonAncestorValue = ancestor.getValue(); } this.commonAncestorLoaded = true; } }
3,159
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AncestorFetcher.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/conflict/AncestorFetcher.java
package org.chronos.chronodb.internal.impl.conflict; import org.apache.commons.lang3.tuple.Pair; import org.chronos.chronodb.api.key.ChronoIdentifier; public interface AncestorFetcher { public Pair<ChronoIdentifier, Object> findCommonAncestor(long transactionTimestmp, ChronoIdentifier source, ChronoIdentifier target); }
388
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
OverwriteWithSourceStrategy.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/conflict/strategies/OverwriteWithSourceStrategy.java
package org.chronos.chronodb.internal.impl.conflict.strategies; import org.chronos.chronodb.api.conflict.AtomicConflict; import org.chronos.chronodb.api.conflict.ConflictResolutionStrategy; public class OverwriteWithSourceStrategy implements ConflictResolutionStrategy { public static final OverwriteWithSourceStrategy INSTANCE = new OverwriteWithSourceStrategy(); protected OverwriteWithSourceStrategy() { } @Override public Object resolve(final AtomicConflict conflict) { return conflict.getSourceValue(); } }
526
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
OverwriteWithTargetStrategy.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/conflict/strategies/OverwriteWithTargetStrategy.java
package org.chronos.chronodb.internal.impl.conflict.strategies; import org.chronos.chronodb.api.conflict.AtomicConflict; import org.chronos.chronodb.api.conflict.ConflictResolutionStrategy; public class OverwriteWithTargetStrategy implements ConflictResolutionStrategy { public static final OverwriteWithTargetStrategy INSTANCE = new OverwriteWithTargetStrategy(); protected OverwriteWithTargetStrategy() { } @Override public Object resolve(final AtomicConflict conflict) { return conflict.getTargetValue(); } }
550
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
DoNotMergeStrategy.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/conflict/strategies/DoNotMergeStrategy.java
package org.chronos.chronodb.internal.impl.conflict.strategies; import org.chronos.chronodb.api.conflict.AtomicConflict; import org.chronos.chronodb.api.conflict.ConflictResolutionStrategy; import org.chronos.chronodb.api.exceptions.ChronoDBCommitConflictException; public class DoNotMergeStrategy implements ConflictResolutionStrategy { public static final DoNotMergeStrategy INSTANCE = new DoNotMergeStrategy(); protected DoNotMergeStrategy() { } @Override public Object resolve(final AtomicConflict conflict) { throw new ChronoDBCommitConflictException("There are conflicting commits on " + conflict.getSourceKey().toQualifiedKey() + " (and potentially others)!"); } }
691
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
CacheStatisticsImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/cache/CacheStatisticsImpl.java
package org.chronos.chronodb.internal.impl.cache; import java.util.concurrent.atomic.AtomicLong; import org.chronos.chronodb.internal.api.cache.ChronoDBCache.CacheStatistics; public class CacheStatisticsImpl implements CacheStatistics { // ===================================================================================================================== // FIELDS // ===================================================================================================================== private AtomicLong hitCount; private AtomicLong missCount; private AtomicLong evictedCount; private AtomicLong rollbackCount; private AtomicLong clearCount; // ===================================================================================================================== // CONSTRUCTOR // ===================================================================================================================== public CacheStatisticsImpl() { this.hitCount = new AtomicLong(0L); this.missCount = new AtomicLong(0L); this.evictedCount = new AtomicLong(0L); this.rollbackCount = new AtomicLong(0L); this.clearCount = new AtomicLong(0L); } // ===================================================================================================================== // PUBLIC API // ===================================================================================================================== @Override public long getCacheHitCount() { return this.hitCount.get(); } @Override public long getCacheMissCount() { return this.missCount.get(); } @Override public long getEvictionCount() { return this.evictedCount.get(); } @Override public long getRollbackCount() { return rollbackCount.get(); } @Override public long getClearCount() { return clearCount.get(); } public CacheStatisticsImpl duplicate() { CacheStatisticsImpl clone = new CacheStatisticsImpl(); clone.hitCount.set(this.getCacheHitCount()); clone.missCount.set(this.getCacheMissCount()); clone.evictedCount.set(this.getEvictionCount()); clone.rollbackCount.set(this.getRollbackCount()); clone.clearCount.set(this.getClearCount()); return clone; } // ===================================================================================================================== // INTERNAL API // ===================================================================================================================== public void registerHit() { this.hitCount.incrementAndGet(); } public void registerMiss() { this.missCount.incrementAndGet(); } public void registerEviction(){ this.evictedCount.incrementAndGet(); } public void registerEvictions(long amount){ this.evictedCount.addAndGet(amount); } public void registerRollback(){ this.rollbackCount.incrementAndGet(); } public void registerClear(){ this.clearCount.incrementAndGet(); } public void reset() { this.hitCount.set(0); this.missCount.set(0); } // ===================================================================================================================== // TO STRING // ===================================================================================================================== @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("CacheStatistics[Hit: "); builder.append(this.getCacheHitCount()); builder.append(", Miss: "); builder.append(this.getCacheMissCount()); builder.append(", Hit Ratio: "); builder.append(this.getCacheHitRatio() * 100.0); builder.append("%]"); return builder.toString(); } }
3,616
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
CacheGetResultImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/cache/CacheGetResultImpl.java
package org.chronos.chronodb.internal.impl.cache; import org.chronos.chronodb.api.exceptions.CacheGetResultNotPresentException; import org.chronos.chronodb.internal.api.cache.CacheGetResult; /** * A straight-forward implementation of {@link CacheGetResult}. * * <p> * Instead of using the constructor, please make use of the static factory methods provided by this class. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * * @param <T> * The return type of the {@link #getValue()} operation. */ public class CacheGetResultImpl<T> implements CacheGetResult<T> { // ===================================================================================================================== // SINGLETON PART // ===================================================================================================================== /** This is the singleton instance of this class representing a cache miss. */ private static final CacheGetResultImpl<?> MISS; static { MISS = new CacheGetResultImpl<>(false, null, -1L); } // ===================================================================================================================== // FACTORY METHODS // ===================================================================================================================== /** * Returns a new instance of this class representing a cache hit with the given value. * * @param value * The value to use as the result of {@link #getValue()} in the new instance. * @param validFrom * The insertion timestamp of the given value into the store, i.e. the greatest change timestamp of the * request key that is less than or equal to the transaction timestamp. Must not be negative. * * @return The new instance. Never <code>null</code>. */ public static <T> CacheGetResultImpl<T> getHit(final T value, final long validFrom) { if (validFrom < 0) { throw new IllegalArgumentException("Precondition violation - argument 'validFrom' must not be negative!"); } return new CacheGetResultImpl<T>(true, value, validFrom); } /** * Returns the singleton instance representing a cache miss. * * @return The singleton "miss" instance. Never <code>null</code>. */ @SuppressWarnings("unchecked") public static <T> CacheGetResultImpl<T> getMiss() { return (CacheGetResultImpl<T>) MISS; } // ===================================================================================================================== // FIELDS // ===================================================================================================================== /** Holds the actual value for this cache get result. Will be <code>null</code> for cache misses. */ private final T value; /** Determines if this instance is a cache hit (<code>true</code>) or a miss (<code>false</code>). */ private final boolean isHit; /** * The insertion timestamp of the given value into the store, i.e. the greatest change timestamp of the request key * that is less than or equal to the transaction timestamp. */ private final long validFrom; // ===================================================================================================================== // CONSTRUCTOR // ===================================================================================================================== /** * Creates a new instance of this class. * * <p> * This constructor is <code>private</code> on purpose because it performs <b>no checks</b> on the arguments. Please * make use of the static methods of this class instead. * * @param isHit * Use <code>true</code> if the new instance should represent a cache hit, or <code>false</code> if the * new instance should represent a cache miss. * * @param value * The actual value to be contained in the result. Will be used as the result for {@link #getValue()} in * the new instance. * * @param validFrom * The insertion timestamp of the given value into the store, i.e. the greatest change timestamp of the * request key that is less than or equal to the transaction timestamp. Should be greater than or equal * to zero for cache hits, and -1 for cache misses. */ private CacheGetResultImpl(final boolean isHit, final T value, final long validFrom) { this.isHit = isHit; this.value = value; this.validFrom = validFrom; } // ===================================================================================================================== // PUBLIC API // ===================================================================================================================== @Override public boolean isHit() { return this.isHit; } @Override public T getValue() throws CacheGetResultNotPresentException { if (this.isHit) { return this.value; } else { throw new CacheGetResultNotPresentException("Do not call #getValue() when #isHit() is FALSE!"); } } @Override public long getValidFrom() throws CacheGetResultNotPresentException { if (this.isHit) { return this.validFrom; } else { throw new CacheGetResultNotPresentException("Do not call #getValidFrom() when #isHit() is FALSE!"); } } // ===================================================================================================================== // HASH CODE & EQUALS // ===================================================================================================================== @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.isHit ? 1231 : 1237); result = prime * result + (this.value == null ? 0 : this.value.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } CacheGetResultImpl<?> other = (CacheGetResultImpl<?>) obj; if (this.isHit != other.isHit) { return false; } if (this.value == null) { if (other.value != null) { return false; } } else if (!this.value.equals(other.value)) { return false; } return true; } // ===================================================================================================================== // TO STRING // ===================================================================================================================== @Override public String toString() { if (this.isHit) { return "CacheGetResult{HIT, value=" + this.getValue() + "}"; } else { return "CacheGetResult{MISS}"; } } }
6,726
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoDBBogusCache.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/cache/bogus/ChronoDBBogusCache.java
package org.chronos.chronodb.internal.impl.cache.bogus; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.internal.api.GetResult; import org.chronos.chronodb.internal.api.cache.CacheGetResult; import org.chronos.chronodb.internal.api.cache.ChronoDBCache; import org.chronos.chronodb.internal.impl.cache.CacheStatisticsImpl; public class ChronoDBBogusCache implements ChronoDBCache { @Override public <T> CacheGetResult<T> get(final String branch, final long timestamp, final QualifiedKey qualifiedKey) { return CacheGetResult.miss(); } @Override public void cache(final String branch, final GetResult<?> queryResult) { // ignore } @Override public void writeThrough(final String branch, final long timestamp, final QualifiedKey key, final Object value) { // ignore } @Override public int size() { return 0; } @Override public int maxSize() { return 0; } @Override public CacheStatistics getStatistics() { return new CacheStatisticsImpl(); } @Override public void resetStatistics() { // ignore } @Override public void clear() { // ignore } @Override public void rollbackToTimestamp(final long timestamp) { // ignore } }
1,204
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
MosaicCache.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/cache/mosaic/MosaicCache.java
package org.chronos.chronodb.internal.impl.cache.mosaic; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.internal.api.GetResult; import org.chronos.chronodb.internal.api.cache.CacheGetResult; import org.chronos.chronodb.internal.api.cache.ChronoDBCache; import org.chronos.chronodb.internal.impl.cache.CacheStatisticsImpl; import org.chronos.chronodb.internal.impl.cache.util.lru.FakeUsageRegistry; import org.chronos.chronodb.internal.impl.cache.util.lru.RangedGetResultUsageRegistry; import org.chronos.chronodb.internal.impl.cache.util.lru.UsageRegistry; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import static com.google.common.base.Preconditions.*; public class MosaicCache implements ChronoDBCache { private final ReadWriteLock lock = new ReentrantReadWriteLock(true); private final Map<String, Map<QualifiedKey, MosaicRow>> contents; private final UsageRegistry<GetResult<?>> lruRegistry; private final CacheStatisticsImpl statistics; private final int maxSize; private int currentSize; // ===================================================================================================================== // CONSTRUCTOR // ===================================================================================================================== public MosaicCache() { this(-1); } public MosaicCache(final int maxSize) { this.contents = new ConcurrentHashMap<>(); this.maxSize = maxSize; if (this.maxSize <= 0) { this.lruRegistry = FakeUsageRegistry.getInstance(); } else { this.lruRegistry = new RangedGetResultUsageRegistry(); } this.currentSize = 0; this.statistics = new CacheStatisticsImpl(); } // ===================================================================================================================== // PUBLIC API // ===================================================================================================================== @Override public <T> CacheGetResult<T> get(final String branch, final long timestamp, final QualifiedKey qualifiedKey) { checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); checkNotNull(qualifiedKey, "Precondition violation - argument 'qualifiedKey' must not be NULL!"); this.lock.readLock().lock(); try { Map<QualifiedKey, MosaicRow> qKeyToRow = this.contents.get(branch); if (qKeyToRow == null) { this.statistics.registerMiss(); return CacheGetResult.miss(); // qKeyToRow = Maps.newConcurrentMap(); // this.contents.put(branch, qKeyToRow); } MosaicRow row = qKeyToRow.get(qualifiedKey); if (row == null) { this.statistics.registerMiss(); return CacheGetResult.miss(); } return row.get(timestamp); } finally { this.lock.readLock().unlock(); } } @Override public void cache(final String branch, final GetResult<?> queryResult) { checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); checkNotNull(queryResult, "Precondition violation - argument 'queryResult' must not be NULL!"); this.lock.writeLock().lock(); try { if (queryResult.getPeriod().isEmpty()) { // can't cache empty validity ranges return; } MosaicRow row = this.getOrCreateRow(branch, queryResult.getRequestedKey()); row.put(queryResult); this.shrinkIfRequired(); } finally { this.lock.writeLock().unlock(); } } @Override public void writeThrough(final String branch, final long timestamp, final QualifiedKey key, final Object value) { checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); this.lock.writeLock().lock(); try { MosaicRow row = this.getOrCreateRow(branch, key); row.writeThrough(timestamp, value); this.shrinkIfRequired(); } finally { this.lock.writeLock().unlock(); } } @Override public void rollbackToTimestamp(final long timestamp) { checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); this.lock.writeLock().lock(); try { // we register the rollback event BEFORE doing it in case // we encounter an error during the process. Registering // the event first will at least make it show up in the // cache statistics. this.statistics.registerRollback(); for (Entry<String, Map<QualifiedKey, MosaicRow>> entry : this.contents.entrySet()) { Map<QualifiedKey, MosaicRow> qKeyToRow = entry.getValue(); // keep a record of all rows that become empty due to the rollback, such that we can purge them // afterwards Set<QualifiedKey> keysWithEmptyRows = Sets.newHashSet(); for (Entry<QualifiedKey, MosaicRow> entry2 : qKeyToRow.entrySet()) { QualifiedKey qKey = entry2.getKey(); MosaicRow row = entry2.getValue(); this.currentSize -= row.rollbackToTimestamp(timestamp); if (row.isEmpty()) { // remember to remove this map entry after we are done iterating keysWithEmptyRows.add(qKey); } } // purge empty entries in the inner map keysWithEmptyRows.forEach(qKey -> { qKeyToRow.get(qKey).detach(); qKeyToRow.remove(qKey); }); } // purge empty entries in the outer map this.contents.entrySet().removeIf(entry -> entry.getValue() == null || entry.getValue().isEmpty()); } finally { this.lock.writeLock().unlock(); } } @Override public void clear() { this.lock.writeLock().lock(); try { // we register the clear event BEFORE doing it in case // we encounter an error during the process. Registering // the event first will at least make it show up in the // cache statistics. this.statistics.registerClear(); // detach all rows this.contents.values().stream().flatMap(entry -> entry.values().stream()).forEach(row -> row.detach()); this.contents.clear(); this.lruRegistry.clear(); this.currentSize = 0; } finally { this.lock.writeLock().unlock(); } } @Override public CacheStatistics getStatistics() { this.lock.readLock().lock(); try { return this.statistics.duplicate(); } finally { this.lock.readLock().unlock(); } } @Override public void resetStatistics() { this.lock.writeLock().lock(); try { this.statistics.reset(); } finally { this.lock.writeLock().unlock(); } } @Override public int size() { return this.currentSize; } @VisibleForTesting public int computedSize() { return this.contents.values().stream().flatMap(map -> map.values().stream()).mapToInt(row -> row.size()).sum(); } @Override public int maxSize() { return this.maxSize; } @VisibleForTesting public int rowCount() { return (int) this.contents.values().stream().flatMap(map -> map.values().stream()).count(); } @VisibleForTesting public int lruListenerCount() { return this.lruRegistry.getListenerCount(); } @VisibleForTesting public int lruSize() { return this.lruRegistry.sizeInElements(); } // ===================================================================================================================== // INTERNAL HELPER METHODS // ===================================================================================================================== private MosaicRow getOrCreateRow(final String branch, final QualifiedKey key) { Map<QualifiedKey, MosaicRow> qKeyToRow = this.contents.get(branch); if (qKeyToRow == null) { qKeyToRow = Maps.newConcurrentMap(); this.contents.put(branch, qKeyToRow); } MosaicRow row = qKeyToRow.get(key); if (row == null) { // create a new row to hold the data row = new MosaicRow(key, this.lruRegistry, this.statistics, (r, delta) -> this.onRowSizeChanged(branch, key, r, delta)); qKeyToRow.put(key, row); } return row; } protected boolean hasMaxSize() { return this.maxSize > 0; } protected void shrinkIfRequired() { if (this.hasMaxSize() == false) { // no max size given -> no need to shrink the size of the cache return; } if (this.lruRegistry.sizeInElements() <= this.maxSize) { // we are still below the maximum allowed memory; no need to clean up return; } // note: removing the least recently used entry will trigger the callback chain, reducing // 'this.currentSize'. this.lruRegistry.removeLeastRecentlyUsedUntil(() -> this.lruRegistry.sizeInElements() <= this.maxSize); } protected void onRowSizeChanged(final String branch, final QualifiedKey key, final MosaicRow row, final long sizeDelta) { this.currentSize += sizeDelta; if (sizeDelta < 0) { this.statistics.registerEvictions(sizeDelta * -1); } if (row.isEmpty()) { row.detach(); Map<QualifiedKey, MosaicRow> qKeyToRow = this.contents.get(branch); if (qKeyToRow != null) { // remove the cache row qKeyToRow.remove(key); // it might be that the entire branch now has no more rows... if (qKeyToRow.isEmpty()) { this.contents.remove(branch); } } } } }
11,113
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
GetResultComparator.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/cache/mosaic/GetResultComparator.java
package org.chronos.chronodb.internal.impl.cache.mosaic; import java.util.Comparator; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.internal.api.GetResult; public class GetResultComparator implements Comparator<GetResult<?>> { // ===================================================================================================================== // SINGLETON PATTERN // ===================================================================================================================== private static GetResultComparator INSTANCE; static { INSTANCE = new GetResultComparator(); } public static GetResultComparator getInstance() { return INSTANCE; } // ===================================================================================================================== // CONSTRUCTOR // ===================================================================================================================== private GetResultComparator() { } // ===================================================================================================================== // PUBLIC API // ===================================================================================================================== @Override public int compare(final GetResult<?> o1, final GetResult<?> o2) { if (o1 == null && o2 == null) { return 0; } else if (o1 != null && o2 == null) { return 1; } else if (o1 == null && o2 != null) { return -1; } else { // for a total ordering, we need to make sure that the requested keys were the same. // If the requested keys were different, we compare them instead. if (o1.getRequestedKey().equals(o2.getRequestedKey()) == false) { QualifiedKey qKey1 = o1.getRequestedKey(); QualifiedKey qKey2 = o2.getRequestedKey(); int keyspaceCompare = qKey1.getKeyspace().compareTo(qKey2.getKeyspace()); if (keyspaceCompare != 0) { return keyspaceCompare; } else { return qKey1.getKey().compareTo(qKey2.getKey()); } } // we want descending order. // Ranges are ordered by their lower bound, which are of type Long. // Long.compareTo(...) creates an ascending order, so we invert it // by multiplying the result by -1. int lowerBoundCompare = Long.compare(o1.getPeriod().getLowerBound(), o2.getPeriod().getLowerBound()) * -1; // if the lower bound comparison is non-zero, we have our ordering. if (lowerBoundCompare != 0) { return lowerBoundCompare; } // the lower-bound compare is zero, so we compare the upper bounds. return Long.compare(o1.getPeriod().getUpperBound(), o2.getPeriod().getUpperBound()) * -1; } } }
2,681
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
MosaicRow.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/cache/mosaic/MosaicRow.java
package org.chronos.chronodb.internal.impl.cache.mosaic; import static com.google.common.base.Preconditions.*; import java.util.Collections; import java.util.Iterator; import java.util.Set; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.internal.api.GetResult; import org.chronos.chronodb.internal.api.Period; import org.chronos.chronodb.internal.api.cache.CacheGetResult; import org.chronos.chronodb.internal.impl.cache.CacheStatisticsImpl; import org.chronos.chronodb.internal.impl.cache.util.lru.UsageRegistry; public class MosaicRow implements UsageRegistry.RemoveListener<GetResult<?>> { private final QualifiedKey rowKey; private final ReadWriteLock lock; private final UsageRegistry<GetResult<?>> lruRegistry; private final Set<GetResult<?>> contents; private final CacheStatisticsImpl statistics; private final RowSizeChangeCallback sizeChangeCallback; public MosaicRow(final QualifiedKey rowKey, final UsageRegistry<GetResult<?>> lruRegistry, final CacheStatisticsImpl statistics, final RowSizeChangeCallback callback) { checkNotNull(rowKey, "Precondition violation - argument 'rowKey' must not be NULL!"); checkNotNull(lruRegistry, "Precondition violation - argument 'lruRegistry' must not be NULL!"); this.rowKey = rowKey; this.lock = new ReentrantReadWriteLock(true); this.lruRegistry = lruRegistry; this.statistics = statistics; this.lruRegistry.addLeastRecentlyUsedRemoveListener(rowKey, this); this.contents = new ConcurrentSkipListSet<>(GetResultComparator.getInstance()); this.sizeChangeCallback = callback; } @SuppressWarnings("unchecked") public <T> CacheGetResult<T> get(final long timestamp) { this.lock.readLock().lock(); try { for (GetResult<?> result : this.contents) { Period range = result.getPeriod(); if (range.contains(timestamp)) { // cache hit // remember in the LRU registry that we had a hit on this element this.lruRegistry.registerUsage(result); // convert into a cache-get-result T value = (T) result.getValue(); this.statistics.registerHit(); return CacheGetResult.hit(value, result.getPeriod().getLowerBound()); } } // cache miss this.statistics.registerMiss(); return CacheGetResult.miss(); } finally { this.lock.readLock().unlock(); } } /** * Adds the given query result into this row. * * @param queryResult * The query result to add. */ public void put(final GetResult<?> queryResult) { // note: we really do need only the read lock here. The contents map can handle // this kind of concurrency easily without locking. boolean changed = false; this.lock.readLock().lock(); try { changed = this.contents.add(queryResult); } finally { this.lock.readLock().unlock(); } // remember in the LRU registry that this element was just added this.lruRegistry.registerUsage(queryResult); if (changed) { this.sizeChangeCallback.onRowSizeChanged(this, 1); } } /** * Writes the given value through this row, at the given timestamp. * * <p> * This method assumes that the given value will have a validity range that is open-ended on the righthand side. * * @param timestamp * The timestamp at which the write-through occurs. Must not be negative. * @param value * The value to write. May be <code>null</code> to indicate a deletion. */ public void writeThrough(final long timestamp, final Object value) { // shorten the "valid to" period of the open-ended entry (if present) to the given timestamp this.limitOpenEndedPeriodEntryToUpperBound(timestamp); // create the new entry Period newPeriod = Period.createOpenEndedRange(timestamp); GetResult<?> newEntry = GetResult.create(this.rowKey, value, newPeriod); boolean changed = false; this.lock.readLock().lock(); try { changed = this.contents.add(newEntry); } finally { this.lock.readLock().unlock(); } this.lruRegistry.registerUsage(newEntry); if (changed) { this.sizeChangeCallback.onRowSizeChanged(this, 1); } } /** * Rolls back this row to the specified timestamp, i.e. removes all entries with a validity range that is either * after, or contains, the given timestamp. * * <p> * This method will <b>not call</b> the {@link RowSizeChangeCallback}! * * @param timestamp * The timestamp to roll back to. Must not be negative. * @return The total number of elements of the cache entries that were removed due to this operation. May be zero, * but never negative. */ public int rollbackToTimestamp(final long timestamp) { this.lock.writeLock().lock(); try { Iterator<GetResult<?>> iterator = this.contents.iterator(); int totalRemovedElements = 0; while (iterator.hasNext()) { GetResult<?> entry = iterator.next(); Period range = entry.getPeriod(); if (range.isAfter(timestamp) || range.contains(timestamp)) { totalRemovedElements += 1; iterator.remove(); } } return totalRemovedElements; } finally { this.lock.writeLock().unlock(); } } /** * If this cache row contains an entry with a period that is open-ended on the righthand side, then this method * limits the upper bound of this period to the given value. * * <p> * If this row contains no entry with an open-ended period, this method has no effect. * * @param timestamp * The timestamp to use as the new upper bound for the validity period, in case that an entry with an * open-ended period exists. Must not be negative. */ public void limitOpenEndedPeriodEntryToUpperBound(final long timestamp) { checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); // get the first entry (highest in cache, latest period) and check if its range needs to be trimmed GetResult<?> firstEntry = this.contents.stream().findFirst().orElse(null); if (firstEntry != null && firstEntry.getPeriod().getUpperBound() > timestamp) { // the range of the entry needs to be trimmed to the current timestamp Period range = firstEntry.getPeriod(); Period newRange = range.setUpperBound(timestamp); GetResult<?> replacementEntry = GetResult.create(this.rowKey, firstEntry.getValue(), newRange); this.lock.writeLock().lock(); try { // note: we need the exclusive lock (write lock) here. The backing set determines equality // of entries based on the comparator which was passed to its constructor. That comparator // compares the validity ranges of the entries. Their compare(...) operation is based on the // lower bound of the period only. Furthermore, the backing set does NOT override an entry // on "set.add(...)" if the entry is already contained according to the comparator. Therefore, // we first need to remove the outdated entry, and then need to add the replacement. It is // crucial that this happens as an atomic operation - if another thread re-inserts the removed // outdated entry before we get the chance to install the replacement, then the outdated entry // will be "stuck" in the cache forever, placing the whole cache in an invalid state. this.contents.remove(firstEntry); this.contents.add(replacementEntry); } finally { this.lock.writeLock().unlock(); } this.lruRegistry.registerUsage(replacementEntry); } } public boolean isEmpty() { return this.contents.size() <= 0; } public int size() { return this.contents.size(); } /** * Returns the internal contents set. * * <p> * This method is intended for testing purposes only. Do not modify the returned set! * * @return The internal contents set. Never <code>null</code>. */ public Set<GetResult<?>> getContents() { return Collections.unmodifiableSet(this.contents); } public void detach() { this.lruRegistry.removeLeastRecentlyUsedListener(this.rowKey, this); } @Override public void objectRemoved(final Object topic, final GetResult<?> element) { this.lock.writeLock().lock(); try { int sizeBefore = this.size(); boolean removed = this.contents.remove(element); if (removed == false) { return; } int sizeDelta = this.size() - sizeBefore; this.sizeChangeCallback.onRowSizeChanged(this, sizeDelta); } finally { this.lock.writeLock().unlock(); } } // ================================================================================================================= // INNER CLASSES // ================================================================================================================= @FunctionalInterface public interface RowSizeChangeCallback { public void onRowSizeChanged(MosaicRow row, int sizeDeltaInElements); } }
8,908
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
RangedGetResultUsageRegistry.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/cache/util/lru/RangedGetResultUsageRegistry.java
package org.chronos.chronodb.internal.impl.cache.util.lru; import org.chronos.chronodb.internal.api.GetResult; public class RangedGetResultUsageRegistry extends DefaultUsageRegistry<GetResult<?>> { public RangedGetResultUsageRegistry() { super(RangedGetResultUsageRegistry::extractTopic); } private static Object extractTopic(final GetResult<?> element) { return element.getRequestedKey(); } }
407
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
FakeUsageRegistry.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/cache/util/lru/FakeUsageRegistry.java
package org.chronos.chronodb.internal.impl.cache.util.lru; import java.util.function.Function; public class FakeUsageRegistry<T> implements UsageRegistry<T> { // ===================================================================================================================== // SINGLETON PATTERN // ===================================================================================================================== private static final FakeUsageRegistry<?> INSTANCE; static { INSTANCE = new FakeUsageRegistry<Object>(); } @SuppressWarnings("unchecked") public static <T> FakeUsageRegistry<T> getInstance() { return (FakeUsageRegistry<T>) INSTANCE; } // ===================================================================================================================== // CONSTRUCTOR // ===================================================================================================================== private FakeUsageRegistry() { } // ===================================================================================================================== // PUBLIC API // ===================================================================================================================== @Override public void registerUsage(final T element) { // do nothing } @Override public int sizeInElements() { // we are always empty return 0; } @Override public void clear() { // do nothing } @Override public void removeLeastRecentlyUsedElement() { // do nothing } @Override public void removeLeastRecentlyUsedElements(final int elementsToRemove) { // do nothing } @Override public void addLeastRecentlyUsedRemoveListener(final Object topic, final RemoveListener<T> handler) { // do nothing } @Override public void removeLeastRecentlyUsedListener(final Object topic, final RemoveListener<T> listener) { // do nothing } @Override public int getListenerCount() { return 0; } @Override public Function<T, Object> getTopicResolutionFunction() { return (element) -> null; } }
2,062
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
UsageRegistry.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/cache/util/lru/UsageRegistry.java
package org.chronos.chronodb.internal.impl.cache.util.lru; import static com.google.common.base.Preconditions.*; import java.util.function.Function; import java.util.function.Supplier; public interface UsageRegistry<T> { public void registerUsage(final T element); public int sizeInElements(); public void clear(); public void removeLeastRecentlyUsedElement(); public Function<T, Object> getTopicResolutionFunction(); public void addLeastRecentlyUsedRemoveListener(Object topic, RemoveListener<T> listener); public void removeLeastRecentlyUsedListener(Object topic, RemoveListener<T> listener); // ===================================================================================================================== // DEFAULT METHODS // ===================================================================================================================== public default void addLeastRecentlyUsedRemoveListenerToAnyTopic(final RemoveListener<T> listener) { checkNotNull(listener, "Precondition violation - argument 'listener' must not be NULL!"); this.addLeastRecentlyUsedRemoveListener(null, listener); } public default void removeLeastRecentlyUsedElements(final int elementsToRemove) { for (int i = 0; i < elementsToRemove; i++) { this.removeLeastRecentlyUsedElement(); } } public default void removeLeastRecentlyUsedUntil(final Supplier<Boolean> decision) { while (decision.get() == false) { this.removeLeastRecentlyUsedElement(); } } public default boolean isEmpty() { return this.sizeInElements() <= 0; } public int getListenerCount(); // ===================================================================================================================== // INNER CLASSES // ===================================================================================================================== public static interface RemoveListener<T> { public void objectRemoved(Object topic, T element); } }
1,967
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
DefaultUsageRegistry.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/cache/util/lru/DefaultUsageRegistry.java
package org.chronos.chronodb.internal.impl.cache.util.lru; import com.google.common.base.Objects; import com.google.common.collect.HashMultimap; import com.google.common.collect.SetMultimap; import com.google.common.collect.Sets; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import static com.google.common.base.Preconditions.*; public class DefaultUsageRegistry<T> implements UsageRegistry<T> { private final Map<Object, Node<T>> valueToNode; private Node<T> leastRecentlyUsedNode; private Node<T> mostRecentlyUsedNode; private final Function<T, Object> topicResolutionFunction; private final Set<RemoveListener<T>> globalRemoveListeners; private final SetMultimap<Object, RemoveListener<T>> topicToRemoveListeners; private boolean isNotifyingListeners; private Set<RemoveListener<T>> globalListenersToRemoveAfterNotification = Sets.newHashSet(); private SetMultimap<Object, RemoveListener<T>> topicListenerstoRemoveAfterNotification = HashMultimap.create(); public DefaultUsageRegistry(final Function<T, Object> topicResolutionFunction) { checkNotNull(topicResolutionFunction, "Precondition violation - argument 'topicResolutionFunction' must not be NULL!"); this.topicResolutionFunction = topicResolutionFunction; this.valueToNode = new ConcurrentHashMap<>(); this.leastRecentlyUsedNode = null; this.mostRecentlyUsedNode = null; this.globalRemoveListeners = Sets.newHashSet(); this.topicToRemoveListeners = HashMultimap.create(); } @Override public Function<T, Object> getTopicResolutionFunction() { return this.topicResolutionFunction; } @Override public synchronized void registerUsage(final T element) { if (element == null) { throw new IllegalArgumentException("Precondition violation - argument 'element' must not be NULL!"); } Node<T> tempNode = this.valueToNode.get(element); if (tempNode == null) { // this is the first time we see this element; add it as MRU. tempNode = new Node<T>(element); this.valueToNode.put(element, tempNode); } // update the position in the list this.setMRU(tempNode); } @Override public int sizeInElements() { return this.valueToNode.size(); } @Override public synchronized void clear() { this.valueToNode.clear(); this.mostRecentlyUsedNode = null; this.leastRecentlyUsedNode = null; } @Override public synchronized void removeLeastRecentlyUsedElement() { Node<T> node = this.leastRecentlyUsedNode; if (node == null) { // no least recently used value -> registry is empty -> nothing to remove return; } T value = node.getValue(); Object topic = this.topicResolutionFunction.apply(value); // remove the element from our value-to-node cache Node<T> removedNode = this.valueToNode.remove(value); // remove the element from the linked list if (this.mostRecentlyUsedNode == this.leastRecentlyUsedNode) { // list contains only one item; drop it this.mostRecentlyUsedNode = null; this.leastRecentlyUsedNode = null; } else if (this.mostRecentlyUsedNode.getNext() == this.leastRecentlyUsedNode) { // list contains exactly 2 items; drop the latter one this.leastRecentlyUsedNode = this.mostRecentlyUsedNode; this.mostRecentlyUsedNode.setNext(null); } else { // the list has more than 2 values this.leastRecentlyUsedNode = node.getPrevious(); if (this.leastRecentlyUsedNode != null) { this.leastRecentlyUsedNode.setNext(null); } } // check if an actual remove happened if (removedNode == null) { // cache content did not change, don't notify listeners return; } this.isNotifyingListeners = true; try { // notify the "global" listeners (i.e. listeners who don't care about the topic) for (RemoveListener<T> listener : this.globalRemoveListeners) { listener.objectRemoved(topic, value); } // notify the topic-based listeners for (RemoveListener<T> listener : this.topicToRemoveListeners.get(topic)) { listener.objectRemoved(topic, value); } } finally { this.isNotifyingListeners = false; // check if there are listeners to remove for (RemoveListener<T> listener : this.globalListenersToRemoveAfterNotification) { this.globalRemoveListeners.remove(listener); } this.globalListenersToRemoveAfterNotification.clear(); for (Entry<Object, RemoveListener<T>> topicListenerEntry : this.topicListenerstoRemoveAfterNotification.entries()) { this.topicToRemoveListeners.remove(topicListenerEntry.getKey(), topicListenerEntry.getValue()); } this.topicListenerstoRemoveAfterNotification.clear(); } } @Override public synchronized void addLeastRecentlyUsedRemoveListener(final Object topic, final RemoveListener<T> listener) { checkNotNull(listener, "Precondition violation - argument 'listener' must not be NULL!"); if (topic == null) { this.globalRemoveListeners.add(listener); } else { this.topicToRemoveListeners.put(topic, listener); } } @Override public synchronized void removeLeastRecentlyUsedListener(final Object topic, final RemoveListener<T> listener) { checkNotNull(listener, "Precondition violation - argument 'listener' must not be NULL!"); if (this.isNotifyingListeners) { if (topic == null) { this.globalListenersToRemoveAfterNotification.add(listener); } else { this.topicListenerstoRemoveAfterNotification.put(topic, listener); } } else { if (topic == null) { this.globalRemoveListeners.remove(listener); } else { this.topicToRemoveListeners.remove(topic, listener); } } } @Override public synchronized int getListenerCount() { int listeners = this.globalRemoveListeners.size(); listeners += this.topicToRemoveListeners.size(); return listeners; } // ===================================================================================================================== // INTERNAL UTILITY METHODS // ===================================================================================================================== private boolean isMRU(final Node<T> node) { if (this.mostRecentlyUsedNode == null) { return false; } return Objects.equal(this.mostRecentlyUsedNode.getValue(), node.getValue()); } private void setMRU(final Node<T> node) { if (this.isMRU(node)) { // we are already the MRU; do nothing return; } if (this.leastRecentlyUsedNode == node) { this.leastRecentlyUsedNode = node.previous; } node.removeFromList(); node.setNext(this.mostRecentlyUsedNode); this.mostRecentlyUsedNode = node; if (node.getNext() == null) { // case 1: the list is completely empty. We add the node as first AND last this.leastRecentlyUsedNode = node; return; } else if (node.getNext().getNext() == null) { // case 2: the list contained one item. We are the first, and our successor is the last. this.leastRecentlyUsedNode = node.getNext(); return; } else { // case 3: the list contained more than one item. MRU updates, LRU does not. return; } } // @SuppressWarnings("unused") // I leave this method here intact for debugging purposes. public String toDebugString() { if (this.mostRecentlyUsedNode == null && this.leastRecentlyUsedNode == null) { return "[]"; } if (this.mostRecentlyUsedNode == this.leastRecentlyUsedNode) { return "[" + this.mostRecentlyUsedNode.getValue() + "]"; } StringBuilder builder = new StringBuilder(); builder.append("["); Node<T> currentNode = this.mostRecentlyUsedNode; String separator = ""; Set<Node<T>> visitedNodes = Sets.newHashSet(); while (currentNode != null) { builder.append(separator); separator = "->"; builder.append(currentNode.getValue()); if (currentNode.getNext() != null) { if (currentNode.getNext().getPrevious() != currentNode) { throw new RuntimeException("BROKEN LINK DETECTED. List so far: " + builder.toString()); } if (currentNode.getPrevious() != null) { if (currentNode.getPrevious().getNext() != currentNode) { throw new RuntimeException("BROKEN LINK DETECTED. List so far: " + builder.toString()); } } } if (visitedNodes.contains(currentNode)) { builder.append("->..."); throw new RuntimeException("CYCLE DETECTED: " + builder.toString()); } visitedNodes.add(currentNode); currentNode = currentNode.getNext(); } builder.append("]"); return builder.toString(); } // ===================================================================================================================== // INNER CLASSES // ===================================================================================================================== private static class Node<E> { private Node<E> previous; private Node<E> next; private E value; public Node(final E value) { this(null, null, value); } public Node(final Node<E> previous, final Node<E> next, final E value) { this.previous = previous; this.next = next; this.value = value; } public Node<E> getNext() { return this.next; } public Node<E> getPrevious() { return this.previous; } public E getValue() { return this.value; } public void setNext(final Node<E> next) { this.next = next; if (this.next != null) { this.next.previous = this; } } public void removeFromList() { if (this.previous != null && this.next != null) { // "this" is in the middle of the list this.previous.next = this.next; this.next.previous = this.previous; } else if (this.previous == null && this.next != null) { // "this" is at the beginning of the list this.next.previous = null; } else if (this.previous != null && this.next == null) { // "this" is at the end of the list this.previous.next = null; } this.next = null; this.previous = null; } } }
11,619
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
StandardQueryTokenStream.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/builder/query/StandardQueryTokenStream.java
package org.chronos.chronodb.internal.impl.builder.query; import java.util.Collections; import java.util.List; import java.util.NoSuchElementException; import org.chronos.chronodb.internal.api.query.QueryTokenStream; import org.chronos.chronodb.internal.impl.query.parser.token.QueryToken; import com.google.common.collect.Lists; public class StandardQueryTokenStream implements QueryTokenStream { private final List<QueryToken> elements; private int currentIndex; public StandardQueryTokenStream(final List<QueryToken> elements) { this.elements = Collections.unmodifiableList(Lists.newArrayList(elements)); this.currentIndex = 0; } @Override public QueryToken getToken() { QueryToken token = this.lookAhead(); this.currentIndex++; return token; } @Override public QueryToken lookAhead() { if (this.hasNextToken() == false) { throw new NoSuchElementException("No more tokens available; stream is empty!"); } return this.elements.get(this.currentIndex); } @Override public boolean hasNextToken() { if (this.currentIndex >= this.elements.size()) { return false; } return true; } @Override public boolean isAtStartOfInput() { return this.currentIndex == 0; } }
1,216
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
StandardQueryBuilderFinalizer.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/builder/query/StandardQueryBuilderFinalizer.java
package org.chronos.chronodb.internal.impl.builder.query; import static com.google.common.base.Preconditions.*; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.internal.api.ChronoDBInternal; import org.chronos.chronodb.internal.api.query.ChronoDBQuery; public class StandardQueryBuilderFinalizer extends AbstractFinalizableQueryBuilder { private final ChronoDBInternal owningDB; private final ChronoDBTransaction tx; private final ChronoDBQuery query; public StandardQueryBuilderFinalizer(final ChronoDBInternal owningDB, final ChronoDBTransaction tx, final ChronoDBQuery query) { checkNotNull(owningDB, "Precondition violation - argument 'owningDB' must not be NULL!"); checkNotNull(tx, "Precondition violation - argument 'tx' must not be NULL!"); checkNotNull(query, "Precondition violation - argument 'query' must not be NULL!"); this.owningDB = owningDB; this.tx = tx; this.query = query; } @Override protected ChronoDBInternal getOwningDB() { return this.owningDB; } @Override protected ChronoDBTransaction getTx() { return this.tx; } @Override protected ChronoDBQuery getQuery() { return this.query; } }
1,188
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
StandardQueryBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/builder/query/StandardQueryBuilder.java
package org.chronos.chronodb.internal.impl.builder.query; import static com.google.common.base.Preconditions.*; import java.util.List; import java.util.Set; import org.chronos.chronodb.api.Branch; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.builder.query.FinalizableQueryBuilder; import org.chronos.chronodb.api.builder.query.QueryBuilder; import org.chronos.chronodb.api.builder.query.QueryBuilderStarter; import org.chronos.chronodb.api.builder.query.WhereBuilder; import org.chronos.chronodb.api.exceptions.ChronoDBQuerySyntaxException; import org.chronos.chronodb.api.query.*; import org.chronos.chronodb.internal.api.ChronoDBInternal; import org.chronos.chronodb.internal.api.query.ChronoDBQuery; import org.chronos.chronodb.internal.api.query.QueryManager; import org.chronos.chronodb.internal.api.query.QueryOptimizer; import org.chronos.chronodb.internal.api.query.QueryParser; import org.chronos.chronodb.internal.api.query.QueryTokenStream; import org.chronos.chronodb.internal.impl.query.TextMatchMode; import org.chronos.chronodb.internal.impl.query.parser.token.AndToken; import org.chronos.chronodb.internal.impl.query.parser.token.BeginToken; import org.chronos.chronodb.internal.impl.query.parser.token.EndOfInputToken; import org.chronos.chronodb.internal.impl.query.parser.token.EndToken; import org.chronos.chronodb.internal.impl.query.parser.token.KeyspaceToken; import org.chronos.chronodb.internal.impl.query.parser.token.NotToken; import org.chronos.chronodb.internal.impl.query.parser.token.OrToken; import org.chronos.chronodb.internal.impl.query.parser.token.QueryToken; import org.chronos.chronodb.internal.impl.query.parser.token.WhereToken; import com.google.common.collect.Lists; public class StandardQueryBuilder implements QueryBuilderStarter { private final ChronoDBInternal owningDB; private final ChronoDBTransaction tx; private final List<QueryToken> tokenList; private WhereToken currentWhereToken; private final QueryBuilderImpl queryBuilder; private final WhereBuilderImpl whereBuilder; private final FinalizableQueryBuilderImpl finalizableBuilder; public StandardQueryBuilder(final ChronoDBInternal owningDB, final ChronoDBTransaction tx) { checkNotNull(owningDB, "Precondition violation - argument 'owningDB' must not be NULL!"); checkNotNull(tx, "Precondition violation - argument 'tx' must not be NULL!"); this.owningDB = owningDB; this.tx = tx; this.tokenList = Lists.newArrayList(); this.queryBuilder = new QueryBuilderImpl(); this.whereBuilder = new WhereBuilderImpl(); this.finalizableBuilder = new FinalizableQueryBuilderImpl(); } @Override public QueryBuilder inKeyspace(final String keyspace) { QueryToken keyspaceToken = new KeyspaceToken(keyspace); this.tokenList.add(keyspaceToken); return this.queryBuilder; } @Override public QueryBuilder inDefaultKeyspace() { QueryToken keyspaceToken = new KeyspaceToken(ChronoDBConstants.DEFAULT_KEYSPACE_NAME); this.tokenList.add(keyspaceToken); return this.queryBuilder; } private class QueryBuilderImpl implements QueryBuilder { @Override public QueryBuilder begin() { QueryToken beginToken = new BeginToken(); StandardQueryBuilder.this.tokenList.add(beginToken); return this; } @Override public QueryBuilder end() { QueryToken endToken = new EndToken(); StandardQueryBuilder.this.tokenList.add(endToken); return this; } @Override public QueryBuilder not() { QueryToken notToken = new NotToken(); StandardQueryBuilder.this.tokenList.add(notToken); return this; } @Override public WhereBuilder where(final String indexName) { if (StandardQueryBuilder.this.currentWhereToken != null) { // this should never happen as such a query won't even compile in Java throw new ChronoDBQuerySyntaxException("Unfinished WHERE clause detected!"); } WhereToken whereToken = new WhereToken(); whereToken.setIndexName(indexName); StandardQueryBuilder.this.currentWhereToken = whereToken; StandardQueryBuilder.this.tokenList.add(whereToken); return StandardQueryBuilder.this.whereBuilder; } } private class WhereBuilderImpl implements WhereBuilder { // ================================================================================================================= // STRING OPERATIONS // ================================================================================================================= @Override public FinalizableQueryBuilder contains(final String text) { checkNotNull(text, "Precondition violation - argument 'text' must not be NULL!"); return this.addStringWhereDetails(StringCondition.CONTAINS, TextMatchMode.STRICT, text); } @Override public FinalizableQueryBuilder containsIgnoreCase(final String text) { checkNotNull(text, "Precondition violation - argument 'text' must not be NULL!"); return this.addStringWhereDetails(StringCondition.CONTAINS, TextMatchMode.CASE_INSENSITIVE, text); } @Override public FinalizableQueryBuilder notContains(final String text) { checkNotNull(text, "Precondition violation - argument 'text' must not be NULL!"); return this.addStringWhereDetails(StringCondition.NOT_CONTAINS, TextMatchMode.STRICT, text); } @Override public FinalizableQueryBuilder notContainsIgnoreCase(final String text) { checkNotNull(text, "Precondition violation - argument 'text' must not be NULL!"); return this.addStringWhereDetails(StringCondition.NOT_CONTAINS, TextMatchMode.CASE_INSENSITIVE, text); } @Override public FinalizableQueryBuilder startsWith(final String text) { checkNotNull(text, "Precondition violation - argument 'text' must not be NULL!"); return this.addStringWhereDetails(StringCondition.STARTS_WITH, TextMatchMode.STRICT, text); } @Override public FinalizableQueryBuilder startsWithIgnoreCase(final String text) { checkNotNull(text, "Precondition violation - argument 'text' must not be NULL!"); return this.addStringWhereDetails(StringCondition.STARTS_WITH, TextMatchMode.CASE_INSENSITIVE, text); } @Override public FinalizableQueryBuilder notStartsWith(final String text) { checkNotNull(text, "Precondition violation - argument 'text' must not be NULL!"); return this.addStringWhereDetails(StringCondition.NOT_STARTS_WITH, TextMatchMode.STRICT, text); } @Override public FinalizableQueryBuilder notStartsWithIgnoreCase(final String text) { checkNotNull(text, "Precondition violation - argument 'text' must not be NULL!"); return this.addStringWhereDetails(StringCondition.NOT_STARTS_WITH, TextMatchMode.CASE_INSENSITIVE, text); } @Override public FinalizableQueryBuilder endsWith(final String text) { checkNotNull(text, "Precondition violation - argument 'text' must not be NULL!"); return this.addStringWhereDetails(StringCondition.ENDS_WITH, TextMatchMode.STRICT, text); } @Override public FinalizableQueryBuilder endsWithIgnoreCase(final String text) { checkNotNull(text, "Precondition violation - argument 'text' must not be NULL!"); return this.addStringWhereDetails(StringCondition.ENDS_WITH, TextMatchMode.CASE_INSENSITIVE, text); } @Override public FinalizableQueryBuilder notEndsWith(final String text) { checkNotNull(text, "Precondition violation - argument 'text' must not be NULL!"); return this.addStringWhereDetails(StringCondition.NOT_ENDS_WITH, TextMatchMode.STRICT, text); } @Override public FinalizableQueryBuilder notEndsWithIgnoreCase(final String text) { checkNotNull(text, "Precondition violation - argument 'text' must not be NULL!"); return this.addStringWhereDetails(StringCondition.NOT_ENDS_WITH, TextMatchMode.CASE_INSENSITIVE, text); } @Override public FinalizableQueryBuilder matchesRegex(final String regex) { checkNotNull(regex, "Precondition violation - argument 'regex' must not be NULL!"); return this.addStringWhereDetails(StringCondition.MATCHES_REGEX, TextMatchMode.STRICT, regex); } @Override public FinalizableQueryBuilder notMatchesRegex(final String regex) { checkNotNull(regex, "Precondition violation - argument 'regex' must not be NULL!"); return this.addStringWhereDetails(StringCondition.NOT_MATCHES_REGEX, TextMatchMode.STRICT, regex); } @Override public FinalizableQueryBuilder matchesRegexIgnoreCase(final String regex) { checkNotNull(regex, "Precondition violation - argument 'regex' must not be NULL!"); return this.addStringWhereDetails(StringCondition.MATCHES_REGEX, TextMatchMode.CASE_INSENSITIVE, regex); } @Override public FinalizableQueryBuilder notMatchesRegexIgnoreCase(final String regex) { checkNotNull(regex, "Precondition violation - argument 'regex' must not be NULL!"); return this.addStringWhereDetails(StringCondition.NOT_MATCHES_REGEX, TextMatchMode.CASE_INSENSITIVE, regex); } @Override public FinalizableQueryBuilder isEqualTo(final String value) { checkNotNull(value, "Precondition violation - argument 'value' must not be NULL!"); return this.addStringWhereDetails(Condition.EQUALS, TextMatchMode.STRICT, value); } @Override public FinalizableQueryBuilder isEqualToIgnoreCase(final String value) { checkNotNull(value, "Precondition violation - argument 'value' must not be NULL!"); return this.addStringWhereDetails(Condition.EQUALS, TextMatchMode.CASE_INSENSITIVE, value); } @Override public FinalizableQueryBuilder isNotEqualTo(final String value) { checkNotNull(value, "Precondition violation - argument 'value' must not be NULL!"); return this.addStringWhereDetails(Condition.NOT_EQUALS, TextMatchMode.STRICT, value); } @Override public FinalizableQueryBuilder isNotEqualToIgnoreCase(final String value) { checkNotNull(value, "Precondition violation - argument 'value' must not be NULL!"); return this.addStringWhereDetails(Condition.NOT_EQUALS, TextMatchMode.CASE_INSENSITIVE, value); } // ================================================================================================================= // LONG OPERATIONS // ================================================================================================================= @Override public FinalizableQueryBuilder isEqualTo(final long value) { return this.addLongWhereDetails(Condition.EQUALS, value); } @Override public FinalizableQueryBuilder isNotEqualTo(final long value) { return this.addLongWhereDetails(Condition.NOT_EQUALS, value); } @Override public FinalizableQueryBuilder isGreaterThan(final long value) { return this.addLongWhereDetails(NumberCondition.GREATER_THAN, value); } @Override public FinalizableQueryBuilder isGreaterThanOrEqualTo(final long value) { return this.addLongWhereDetails(NumberCondition.GREATER_EQUAL, value); } @Override public FinalizableQueryBuilder isLessThan(final long value) { return this.addLongWhereDetails(NumberCondition.LESS_THAN, value); } @Override public FinalizableQueryBuilder isLessThanOrEqualTo(final long value) { return this.addLongWhereDetails(NumberCondition.LESS_EQUAL, value); } // ================================================================================================================= // DOUBLE METHODS // ================================================================================================================= @Override public FinalizableQueryBuilder isEqualTo(final double value, final double tolerance) { return this.addDoubleWhereDetails(Condition.EQUALS, value, tolerance); } @Override public FinalizableQueryBuilder isNotEqualTo(final double value, final double tolerance) { return this.addDoubleWhereDetails(Condition.NOT_EQUALS, value, tolerance); } @Override public FinalizableQueryBuilder isLessThan(final double value) { return this.addDoubleWhereDetails(NumberCondition.LESS_THAN, value, 0); } @Override public FinalizableQueryBuilder isLessThanOrEqualTo(final double value) { return this.addDoubleWhereDetails(NumberCondition.LESS_EQUAL, value, 0); } @Override public FinalizableQueryBuilder isGreaterThan(final double value) { return this.addDoubleWhereDetails(NumberCondition.GREATER_THAN, value, 0); } @Override public FinalizableQueryBuilder isGreaterThanOrEqualTo(final double value) { return this.addDoubleWhereDetails(NumberCondition.GREATER_EQUAL, value, 0); } // ================================================================================================================= // SET METHODS // ================================================================================================================= @Override public FinalizableQueryBuilder inStringsIgnoreCase(final Set<String> values) { return this.addSetStringWhereDetails(StringContainmentCondition.WITHIN, TextMatchMode.CASE_INSENSITIVE, values); } @Override public FinalizableQueryBuilder inStrings(final Set<String> values) { return this.addSetStringWhereDetails(StringContainmentCondition.WITHIN, TextMatchMode.STRICT, values); } @Override public FinalizableQueryBuilder notInStringsIgnoreCase(final Set<String> values) { return this.addSetStringWhereDetails(StringContainmentCondition.WITHOUT, TextMatchMode.CASE_INSENSITIVE, values); } @Override public FinalizableQueryBuilder notInStrings(final Set<String> values) { return this.addSetStringWhereDetails(StringContainmentCondition.WITHOUT, TextMatchMode.STRICT, values); } @Override public FinalizableQueryBuilder inLongs(final Set<Long> values) { return this.addSetLongWhereDetails(LongContainmentCondition.WITHIN, values); } @Override public FinalizableQueryBuilder notInLongs(final Set<Long> values) { return this.addSetLongWhereDetails(LongContainmentCondition.WITHOUT, values); } @Override public FinalizableQueryBuilder inDoubles(final Set<Double> values, final double tolerance) { return this.addSetDoubleWhereDetails(DoubleContainmentCondition.WITHIN, values, tolerance); } @Override public FinalizableQueryBuilder notInDoubles(final Set<Double> values, final double tolerance) { return this.addSetDoubleWhereDetails(DoubleContainmentCondition.WITHOUT, values, tolerance); } // ================================================================================================================= // HELPER METHODS // ================================================================================================================= private FinalizableQueryBuilder addStringWhereDetails(final StringCondition condition, final TextMatchMode matchMode, final String text) { if (StandardQueryBuilder.this.currentWhereToken == null) { // this should never happen as such a query won't even compile in Java throw new ChronoDBQuerySyntaxException("Received '" + condition.getInfix() + "', but no WHERE clause is open!"); } StandardQueryBuilder.this.currentWhereToken.setStringWhereDetails(condition, matchMode, text); // we are done with that WHERE clause StandardQueryBuilder.this.currentWhereToken = null; return StandardQueryBuilder.this.finalizableBuilder; } private FinalizableQueryBuilder addLongWhereDetails(final NumberCondition condition, final long compareValue) { if (StandardQueryBuilder.this.currentWhereToken == null) { // this should never happen as such a query won't even compile in Java throw new ChronoDBQuerySyntaxException("Received '" + condition.getInfix() + "', but no WHERE clause is open!"); } StandardQueryBuilder.this.currentWhereToken.setLongWhereDetails(condition, compareValue); // we are done with that WHERE clause StandardQueryBuilder.this.currentWhereToken = null; return StandardQueryBuilder.this.finalizableBuilder; } private FinalizableQueryBuilder addDoubleWhereDetails(final NumberCondition condition, final double compareValue, final double tolerance) { if (StandardQueryBuilder.this.currentWhereToken == null) { // this should never happen as such a query won't even compile in Java throw new ChronoDBQuerySyntaxException("Received '" + condition.getInfix() + "', but no WHERE clause is open!"); } StandardQueryBuilder.this.currentWhereToken.setDoubleDetails(condition, compareValue, tolerance); // we are done with that WHERE clause StandardQueryBuilder.this.currentWhereToken = null; return StandardQueryBuilder.this.finalizableBuilder; } private FinalizableQueryBuilder addSetStringWhereDetails(final StringContainmentCondition condition, final TextMatchMode matchMode, final Set<String> text) { if (StandardQueryBuilder.this.currentWhereToken == null) { // this should never happen as such a query won't even compile in Java throw new ChronoDBQuerySyntaxException("Received '" + condition.getInfix() + "', but no WHERE clause is open!"); } StandardQueryBuilder.this.currentWhereToken.setSetStringWhereDetails(condition, matchMode, text); // we are done with that WHERE clause StandardQueryBuilder.this.currentWhereToken = null; return StandardQueryBuilder.this.finalizableBuilder; } private FinalizableQueryBuilder addSetLongWhereDetails(final LongContainmentCondition condition, final Set<Long> compareValues) { if (StandardQueryBuilder.this.currentWhereToken == null) { // this should never happen as such a query won't even compile in Java throw new ChronoDBQuerySyntaxException("Received '" + condition.getInfix() + "', but no WHERE clause is open!"); } StandardQueryBuilder.this.currentWhereToken.setSetLongWhereDetails(condition, compareValues); // we are done with that WHERE clause StandardQueryBuilder.this.currentWhereToken = null; return StandardQueryBuilder.this.finalizableBuilder; } private FinalizableQueryBuilder addSetDoubleWhereDetails(final DoubleContainmentCondition condition, final Set<Double> compareValues, final double tolerance) { if (StandardQueryBuilder.this.currentWhereToken == null) { // this should never happen as such a query won't even compile in Java throw new ChronoDBQuerySyntaxException("Received '" + condition.getInfix() + "', but no WHERE clause is open!"); } StandardQueryBuilder.this.currentWhereToken.setSetDoubleDetails(condition, compareValues, tolerance); // we are done with that WHERE clause StandardQueryBuilder.this.currentWhereToken = null; return StandardQueryBuilder.this.finalizableBuilder; } } private class FinalizableQueryBuilderImpl extends AbstractFinalizableQueryBuilder implements FinalizableQueryBuilder { @Override protected ChronoDBQuery getQuery() { return this.toQuery(); } @Override protected ChronoDBInternal getOwningDB() { return StandardQueryBuilder.this.owningDB; } @Override protected ChronoDBTransaction getTx() { return StandardQueryBuilder.this.tx; } @Override public ChronoDBQuery toQuery() { // add the End-Of-Input token to the stream QueryToken endOfInputToken = new EndOfInputToken(); StandardQueryBuilder.this.tokenList.add(endOfInputToken); // parse the query ChronoDBQuery query = this.createOptimizedQuery(); return query; } @Override public long count() { // add the End-Of-Input token to the stream QueryToken endOfInputToken = new EndOfInputToken(); StandardQueryBuilder.this.tokenList.add(endOfInputToken); // parse the query ChronoDBQuery query = this.createOptimizedQuery(); // evaluate the query String branchName = StandardQueryBuilder.this.tx.getBranchName(); Branch branch = StandardQueryBuilder.this.owningDB.getBranchManager().getBranch(branchName); long timestamp = StandardQueryBuilder.this.tx.getTimestamp(); return StandardQueryBuilder.this.owningDB.getIndexManager().evaluateCount(timestamp, branch, query); } @Override public QueryBuilder and() { QueryToken andToken = new AndToken(); StandardQueryBuilder.this.tokenList.add(andToken); return StandardQueryBuilder.this.queryBuilder; } @Override public QueryBuilder or() { QueryToken orToken = new OrToken(); StandardQueryBuilder.this.tokenList.add(orToken); return StandardQueryBuilder.this.queryBuilder; } @Override public FinalizableQueryBuilder begin() { QueryToken beginToken = new BeginToken(); StandardQueryBuilder.this.tokenList.add(beginToken); return StandardQueryBuilder.this.finalizableBuilder; } @Override public FinalizableQueryBuilder end() { QueryToken endToken = new EndToken(); StandardQueryBuilder.this.tokenList.add(endToken); return StandardQueryBuilder.this.finalizableBuilder; } @Override public FinalizableQueryBuilder not() { QueryToken notToken = new NotToken(); StandardQueryBuilder.this.tokenList.add(notToken); return StandardQueryBuilder.this.finalizableBuilder; } private ChronoDBQuery createOptimizedQuery() { QueryTokenStream tokenStream = new StandardQueryTokenStream(StandardQueryBuilder.this.tokenList); QueryManager queryManager = StandardQueryBuilder.this.owningDB.getQueryManager(); QueryParser parser = queryManager.getQueryParser(); ChronoDBQuery query = parser.parse(tokenStream); QueryOptimizer optimizer = queryManager.getQueryOptimizer(); return optimizer.optimize(query); } } }
21,377
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AbstractFinalizableQueryBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/builder/query/AbstractFinalizableQueryBuilder.java
package org.chronos.chronodb.internal.impl.builder.query; import java.util.Iterator; import java.util.Map.Entry; import org.chronos.chronodb.api.Branch; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.builder.query.QueryBuilderFinalizer; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.internal.api.ChronoDBInternal; import org.chronos.chronodb.internal.api.query.ChronoDBQuery; import org.chronos.chronodb.internal.util.ImmutableMapEntry; public abstract class AbstractFinalizableQueryBuilder implements QueryBuilderFinalizer { @Override public Iterator<QualifiedKey> getKeys() { ChronoDBQuery query = this.getQuery(); // evaluate the query Branch branch = this.getBranch(); long timestamp = this.getTx().getTimestamp(); return this.getOwningDB().getIndexManager().evaluate(timestamp, branch, query); } @Override public Iterator<Entry<QualifiedKey, Object>> getQualifiedResult() { ChronoDBQuery query = this.getQuery(); // evaluate the query Branch branch = this.getBranch(); long timestamp = this.getTx().getTimestamp(); Iterator<QualifiedKey> keyIterator = this.getOwningDB().getIndexManager().evaluate(timestamp, branch, query); return new QualifiedResultIterator(keyIterator); } @Override public Iterator<Entry<String, Object>> getResult() { ChronoDBQuery query = this.getQuery(); // evaluate the query Branch branch = this.getBranch(); long timestamp = this.getTx().getTimestamp(); Iterator<QualifiedKey> keyIterator = this.getOwningDB().getIndexManager().evaluate(timestamp, branch, query); return new UnqualifiedResultIterator(keyIterator); } @Override public Iterator<Object> getValues() { ChronoDBQuery query = this.getQuery(); // evaluate the query Branch branch = this.getBranch(); long timestamp = this.getTx().getTimestamp(); Iterator<QualifiedKey> keyIterator = this.getOwningDB().getIndexManager().evaluate(timestamp, branch, query); return new ValuesResultIterator(keyIterator); } protected Branch getBranch() { String branchName = this.getTx().getBranchName(); Branch branch = this.getOwningDB().getBranchManager().getBranch(branchName); return branch; } protected abstract ChronoDBQuery getQuery(); protected abstract ChronoDBInternal getOwningDB(); protected abstract ChronoDBTransaction getTx(); private class QualifiedResultIterator implements Iterator<Entry<QualifiedKey, Object>> { private final Iterator<QualifiedKey> keysIterator; public QualifiedResultIterator(final Iterator<QualifiedKey> keysIterator) { this.keysIterator = keysIterator; } @Override public boolean hasNext() { return this.keysIterator.hasNext(); } @Override public Entry<QualifiedKey, Object> next() { QualifiedKey qKey = this.keysIterator.next(); Object value = AbstractFinalizableQueryBuilder.this.getTx().get(qKey.getKeyspace(), qKey.getKey()); Entry<QualifiedKey, Object> entry = ImmutableMapEntry.create(qKey, value); return entry; } } private class UnqualifiedResultIterator implements Iterator<Entry<String, Object>> { private final Iterator<QualifiedKey> keysIterator; public UnqualifiedResultIterator(final Iterator<QualifiedKey> keysIterator) { this.keysIterator = keysIterator; } @Override public boolean hasNext() { return this.keysIterator.hasNext(); } @Override public Entry<String, Object> next() { QualifiedKey qKey = this.keysIterator.next(); String keyspace = qKey.getKeyspace(); String key = qKey.getKey(); Object value = AbstractFinalizableQueryBuilder.this.getTx().get(keyspace, key); Entry<String, Object> entry = ImmutableMapEntry.create(key, value); return entry; } } private class ValuesResultIterator implements Iterator<Object> { private final Iterator<QualifiedKey> keysIterator; public ValuesResultIterator(final Iterator<QualifiedKey> keysIterator) { this.keysIterator = keysIterator; } @Override public boolean hasNext() { return this.keysIterator.hasNext(); } @Override public Object next() { QualifiedKey qKey = this.keysIterator.next(); Object value = AbstractFinalizableQueryBuilder.this.getTx().get(qKey.getKeyspace(), qKey.getKey()); return value; } } }
4,266
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
DefaultTransactionBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/builder/transaction/DefaultTransactionBuilder.java
package org.chronos.chronodb.internal.impl.builder.transaction; import static com.google.common.base.Preconditions.*; import java.util.Date; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.DuplicateVersionEliminationMode; import org.chronos.chronodb.api.builder.transaction.ChronoDBTransactionBuilder; import org.chronos.chronodb.api.conflict.ConflictResolutionStrategy; import org.chronos.chronodb.internal.api.ChronoDBInternal; import org.chronos.chronodb.internal.api.MutableTransactionConfiguration; import org.chronos.chronodb.internal.impl.DefaultTransactionConfiguration; public class DefaultTransactionBuilder implements ChronoDBTransactionBuilder { private final ChronoDBInternal owningDB; private final MutableTransactionConfiguration configuration; public DefaultTransactionBuilder(final ChronoDBInternal owningDB) { checkNotNull(owningDB, "Precondition violation - argument 'owningDB' must not be NULL!"); this.owningDB = owningDB; this.configuration = new DefaultTransactionConfiguration(); // by default, we inherit some settings from the owning database this.configuration .setConflictResolutionStrategy(this.owningDB.getConfiguration().getConflictResolutionStrategy()); this.configuration.setDuplicateVersionEliminationMode( this.owningDB.getConfiguration().getDuplicateVersionEliminationMode()); } @Override public ChronoDBTransaction build() { this.configuration.freeze(); return this.owningDB.tx(this.configuration); } @Override public ChronoDBTransactionBuilder readOnly() { this.configuration.setReadOnly(true); return this; } @Override public ChronoDBTransactionBuilder threadSafe() { this.configuration.setThreadSafe(true); return this; } @Override public ChronoDBTransactionBuilder atDate(final Date date) { checkNotNull(date, "Precondition violation - argument 'date' must not be NULL!"); this.configuration.setTimestamp(date.getTime()); return this; } @Override public ChronoDBTransactionBuilder atTimestamp(final long timestamp) { checkArgument(timestamp >= 0, "Precondition Violation - argument 'timestamp' must not be negative!"); this.configuration.setTimestamp(timestamp); return this; } @Override public ChronoDBTransactionBuilder onBranch(final String branchName) { checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!"); this.configuration.setBranch(branchName); return this; } @Override public ChronoDBTransactionBuilder withConflictResolutionStrategy(final ConflictResolutionStrategy strategy) { checkNotNull(strategy, "Precondition violation - argument 'strategy' must not be NULL!"); this.configuration.setConflictResolutionStrategy(strategy); return this; } @Override public ChronoDBTransactionBuilder withDuplicateVersionEliminationMode(final DuplicateVersionEliminationMode mode) { checkNotNull(mode, "Precondition violation - argument 'mode' must not be NULL!"); this.configuration.setDuplicateVersionEliminationMode(mode); return this; } }
3,063
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AbstractChronoDBFinalizableBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/builder/database/AbstractChronoDBFinalizableBuilder.java
package org.chronos.chronodb.internal.impl.builder.database; import static com.google.common.base.Preconditions.*; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.CommitMetadataFilter; import org.chronos.chronodb.api.DuplicateVersionEliminationMode; import org.chronos.chronodb.api.builder.database.ChronoDBFinalizableBuilder; import org.chronos.chronodb.api.conflict.ConflictResolutionStrategy; import org.chronos.chronodb.internal.api.ChronoDBConfiguration; import org.chronos.chronodb.internal.api.ChronoDBFactoryInternal; public abstract class AbstractChronoDBFinalizableBuilder<SELF extends ChronoDBFinalizableBuilder<?>> extends AbstractChronoDBBuilder<SELF> implements ChronoDBFinalizableBuilder<SELF> { @Override @SuppressWarnings("unchecked") public SELF withLruCacheOfSize(final int maxSize) { if (maxSize > 0) { this.withProperty(ChronoDBConfiguration.CACHING_ENABLED, "true"); this.withProperty(ChronoDBConfiguration.CACHE_MAX_SIZE, String.valueOf(maxSize)); } else { this.withProperty(ChronoDBConfiguration.CACHING_ENABLED, "false"); } return (SELF) this; } @Override public SELF assumeCachedValuesAreImmutable(final boolean value) { return this.withProperty(ChronoDBConfiguration.ASSUME_CACHE_VALUES_ARE_IMMUTABLE, String.valueOf(value)); } @Override @SuppressWarnings("unchecked") public SELF withLruQueryCacheOfSize(final int maxSize) { if (maxSize > 0) { this.withProperty(ChronoDBConfiguration.QUERY_CACHE_ENABLED, "true"); this.withProperty(ChronoDBConfiguration.QUERY_CACHE_MAX_SIZE, String.valueOf(maxSize)); } else { this.withProperty(ChronoDBConfiguration.QUERY_CACHE_ENABLED, "false"); } return (SELF) this; } @Override @SuppressWarnings("unchecked") public SELF withDuplicateVersionElimination(final boolean useDuplicateVersionElimination) { DuplicateVersionEliminationMode mode = DuplicateVersionEliminationMode.DISABLED; if (useDuplicateVersionElimination) { mode = DuplicateVersionEliminationMode.ON_COMMIT; } return this.withProperty(ChronoDBConfiguration.DUPLICATE_VERSION_ELIMINATION_MODE, mode.toString()); } @Override @SuppressWarnings("unchecked") public SELF withConflictResolutionStrategy(final ConflictResolutionStrategy strategy) { checkNotNull(strategy, "Precondition violation - argument 'strategy' must not be NULL!"); return this.withProperty(ChronoDBConfiguration.COMMIT_CONFLICT_RESOLUTION_STRATEGY, strategy.getClass().getName()); } @Override public SELF withCommitMetadataFilter(final Class<? extends CommitMetadataFilter> filterClass) { if(filterClass == null){ return this.withProperty(ChronoDBConfiguration.COMMIT_METADATA_FILTER_CLASS, ""); }else{ return this.withProperty(ChronoDBConfiguration.COMMIT_METADATA_FILTER_CLASS, filterClass.getName()); } } public SELF withPerformanceLoggingForCommits(final boolean enablePerformanceLoggingForCommits){ return this.withProperty(ChronoDBConfiguration.PERFORMANCE_LOGGING_FOR_COMMITS, String.valueOf(enablePerformanceLoggingForCommits)); } @Override public ChronoDB build() { return ChronoDBFactoryInternal.INSTANCE.create(this.getConfiguration()); } }
3,181
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoDBBaseBuilderImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/builder/database/ChronoDBBaseBuilderImpl.java
package org.chronos.chronodb.internal.impl.builder.database; import org.apache.commons.configuration2.Configuration; import org.apache.commons.configuration2.MapConfiguration; import org.chronos.chronodb.api.builder.database.ChronoDBBackendBuilder; import org.chronos.chronodb.api.builder.database.ChronoDBBaseBuilder; import org.chronos.chronodb.api.builder.database.ChronoDBPropertyFileBuilder; import org.chronos.chronodb.api.exceptions.ChronoDBConfigurationException; import java.io.File; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Properties; import static com.google.common.base.Preconditions.*; public class ChronoDBBaseBuilderImpl extends AbstractChronoDBBuilder<ChronoDBBaseBuilderImpl> implements ChronoDBBaseBuilder { @Override public ChronoDBPropertyFileBuilder fromPropertiesFile(final File file) { checkNotNull(file, "Precondition violation - argument 'file' must not be NULL!"); return new ChronoDBPropertyFileBuilderImpl(file); } @Override public ChronoDBPropertyFileBuilder fromPropertiesFile(final String filePath) { checkNotNull(filePath, "Precondition violation - argument 'filePath' must not be NULL!"); return new ChronoDBPropertyFileBuilderImpl(filePath); } @Override public ChronoDBPropertyFileBuilder fromConfiguration(final Configuration configuration) { checkNotNull(configuration, "Precondition violation - argument 'configuration' must not be NULL!"); return new ChronoDBPropertyFileBuilderImpl(configuration); } @Override public ChronoDBPropertyFileBuilder fromProperties(final Properties properties) { checkNotNull(properties, "Precondition violation - argument 'properties' must not be NULL!"); Configuration configuration = new MapConfiguration(properties); return this.fromConfiguration(configuration); } @Override @SuppressWarnings("unchecked") public <T extends ChronoDBBackendBuilder> T database(final Class<T> builderClass) { checkNotNull(builderClass, "Precondition violation - argument 'builderClass' must not be NULL!"); try { Constructor<? extends ChronoDBBackendBuilder> constructor = builderClass.getConstructor(); return (T) constructor.newInstance(); } catch (NoSuchMethodException | InstantiationException | InvocationTargetException | IllegalAccessException e) { throw new ChronoDBConfigurationException("Failed to instantiate Database Builder of type '" + builderClass.getName() + "'!", e); } } }
2,473
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoDBPropertyFileBuilderImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/builder/database/ChronoDBPropertyFileBuilderImpl.java
package org.chronos.chronodb.internal.impl.builder.database; import static com.google.common.base.Preconditions.*; import java.io.File; import java.util.Iterator; import org.apache.commons.configuration2.Configuration; import org.chronos.chronodb.api.builder.database.ChronoDBPropertyFileBuilder; public class ChronoDBPropertyFileBuilderImpl extends AbstractChronoDBFinalizableBuilder<ChronoDBPropertyFileBuilder> implements ChronoDBPropertyFileBuilder { public ChronoDBPropertyFileBuilderImpl(final String propertiesFilePath) { checkNotNull(propertiesFilePath, "Precondition violation - argument 'propertiesFilePath' must not be NULL!"); this.withPropertiesFile(propertiesFilePath); } public ChronoDBPropertyFileBuilderImpl(final File propertiesFile) { checkNotNull(propertiesFile, "Precondition violation - argument 'propertiesFile' must not be NULL!"); this.withPropertiesFile(propertiesFile); } public ChronoDBPropertyFileBuilderImpl(final Configuration apacheConfiguration) { checkNotNull(apacheConfiguration, "Precondition violation - argument 'apacheConfiguration' must not be NULL!"); Iterator<String> keyIterator = apacheConfiguration.getKeys(); while (keyIterator.hasNext()) { String key = keyIterator.next(); String value = String.valueOf(apacheConfiguration.getProperty(key)); this.withProperty(key, value); } } }
1,366
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AbstractChronoDBBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/builder/database/AbstractChronoDBBuilder.java
package org.chronos.chronodb.internal.impl.builder.database; import org.apache.commons.configuration2.Configuration; import org.apache.commons.configuration2.MapConfiguration; import org.chronos.common.builder.AbstractChronoBuilder; import org.chronos.common.builder.ChronoBuilder; public abstract class AbstractChronoDBBuilder<SELF extends ChronoBuilder<?>> extends AbstractChronoBuilder<SELF> implements ChronoBuilder<SELF> { protected Configuration getConfiguration() { return new MapConfiguration(this.getProperties()); } }
538
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoDBFactoryImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/builder/database/ChronoDBFactoryImpl.java
package org.chronos.chronodb.internal.impl.builder.database; import static com.google.common.base.Preconditions.*; import org.apache.commons.configuration2.Configuration; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.builder.database.ChronoDBBaseBuilder; import org.chronos.chronodb.api.builder.database.spi.ChronoDBBackendProvider; import org.chronos.chronodb.internal.api.ChronoDBConfiguration; import org.chronos.chronodb.internal.api.ChronoDBFactoryInternal; import org.chronos.chronodb.internal.api.ChronoDBInternal; import org.chronos.chronodb.internal.impl.base.builder.database.service.ChronoDBBackendProviderService; public class ChronoDBFactoryImpl implements ChronoDBFactoryInternal { // ================================================================================================================= // INTERNAL UTILITY METHODS // ================================================================================================================= @Override public ChronoDB create(final Configuration configuration) { checkNotNull(configuration, "Precondition violation - argument 'configuration' must not be NULL!"); String backend = configuration.getString(ChronoDBConfiguration.STORAGE_BACKEND); if(backend == null || backend.trim().isEmpty()){ throw new IllegalArgumentException("The given configuration does not specify a storage backend. Please specify a value for the key '" + ChronoDBConfiguration.STORAGE_BACKEND + "' in your configuration."); } ChronoDBBackendProvider builderProvider = ChronoDBBackendProviderService.getInstance().getBackendProvider(backend); ChronoDBInternal db = builderProvider.instantiateChronoDB(configuration); db.postConstruct(); return db; } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public ChronoDBBaseBuilder create() { return new ChronoDBBaseBuilderImpl(); } }
2,095
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
CommitMetadataStore.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/api/CommitMetadataStore.java
package org.chronos.chronodb.internal.api; import com.google.common.collect.Sets; import org.chronos.chronodb.api.Branch; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.Order; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import java.util.Set; import static com.google.common.base.Preconditions.*; /** * A {@link CommitMetadataStore} is a store in the chronos backend that contains metadata objects for commit operations. * * <p> * Any commit may have a metadata object attached. For details, please refer to {@link ChronoDBTransaction#commit(Object)}. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API */ public interface CommitMetadataStore { /** * Returns an iterator over all timestamps where commits have occurred, bounded between <code>from</code> and <code>to</code>, in descending order. * * <p> * If the <code>from</code> value is greater than the <code>to</code> value, this method always returns an empty iterator. * * @param from The lower bound of the time range to look for commits in (inclusive). Must not be negative. * @param to The upper bound of the time range to look for commits in (inclusive). Must not be negative. * @param includeSystemInternalCommits Whether or not to include system-internal commits. * @return The iterator over the commit timestamps in the given time range, in descending order. May be empty, but never <code>null</code>. */ public default Iterator<Long> getCommitTimestampsBetween(final long from, final long to, final boolean includeSystemInternalCommits) { return this.getCommitTimestampsBetween(from, to, Order.DESCENDING, includeSystemInternalCommits); } /** * Returns an iterator over all timestamps where commits have occurred, bounded between <code>from</code> and <code>to</code>. * * <p> * If the <code>from</code> value is greater than the <code>to</code> value, this method always returns an empty iterator. * * @param from The lower bound of the time range to look for commits in (inclusive). Must not be negative. * @param to The upper bound of the time range to look for commits in (inclusive). Must not be negative. * @param order The order of the returned timestamps. Must not be <code>null</code>. * @param includeSystemInternalCommits Whether or not to include system-internal commits. * @return The iterator over the commit timestamps in the given time range. May be empty, but never <code>null</code>. */ public Iterator<Long> getCommitTimestampsBetween(long from, long to, Order order, boolean includeSystemInternalCommits); /** * Returns an iterator over the entries of commit timestamp and associated metadata, bounded between <code>from</code> and <code>to</code>, in descending order. * * <p> * If the <code>from</code> value is greater than the <code>to</code> value, this method always returns an empty iterator. * * <p> * Please keep in mind that some commits may not have any metadata attached. In this case, the {@linkplain Entry#getValue() value} component of the {@link Entry} will be set to <code>null</code>. * * @param from The lower bound of the time range to look for commits in (inclusive). Must not be negative. * @param to The upper bound of the time range to look for commits in (inclusive). Must not be negative. * @param includeSystemInternalCommits Whether or not to include system-internal commits. * @return An iterator over the commits in the given time range in descending order. The containd entries have the timestamp as the first component and the associated metadata as their second component (which may be <code>null</code>). May be empty, but never <code>null</code>. */ public default Iterator<Entry<Long, Object>> getCommitMetadataBetween(final long from, final long to, final boolean includeSystemInternalCommits) { return this.getCommitMetadataBetween(from, to, Order.DESCENDING, includeSystemInternalCommits); } /** * Returns an iterator over the entries of commit timestamp and associated metadata, bounded between <code>from</code> and <code>to</code>. * * <p> * If the <code>from</code> value is greater than the <code>to</code> value, this method always returns an empty iterator. * * <p> * Please keep in mind that some commits may not have any metadata attached. In this case, the {@linkplain Entry#getValue() value} component of the {@link Entry} will be set to <code>null</code>. * * @param from The lower bound of the time range to look for commits in (inclusive). Must not be negative. * @param to The upper bound of the time range to look for commits in (inclusive). Must not be negative. * @param order The order of the returned commits. Must not be <code>null</code>. * @param includeSystemInternalCommits Whether or not to include system-internal commits. * @return An iterator over the commits in the given time range. The containd entries have the timestamp as the first component and the associated metadata as their second component (which may be <code>null</code>). May be empty, but never <code>null</code>. */ public Iterator<Entry<Long, Object>> getCommitMetadataBetween(long from, long to, Order order, boolean includeSystemInternalCommits); /** * Returns an iterator over commit timestamps in a paged fashion. * * <p> * For example, calling {@code getCommitTimestampsPaged(10000, 100, 0, Order.DESCENDING)} will give the latest 100 commit timestamps that have occurred before timestamp 10000. Calling {@code getCommitTimestampsPaged(123456, 200, 2, Order.DESCENDING} will return 200 commit timestamps, skipping the 400 latest commit timestamps, which are smaller than 123456. * * @param minTimestamp The minimum timestamp to consider (inclusive). All lower timestamps will be excluded from the pagination. * @param maxTimestamp The highest timestamp to consider (inclusive). All higher timestamps will be excluded from the pagination. * @param pageSize The size of the page, i.e. the maximum number of elements allowed to be contained in the resulting iterator. Must be greater than zero. * @param pageIndex The index of the page to retrieve. Must not be negative. * @param order The desired ordering for the commit timestamps * @param includeSystemInternalCommits Whether or not to include system-internal commits. * @return An iterator that contains the commit timestamps for the requested page. Never <code>null</code>, may be empty. If the requested page does not exist, this iterator will always be empty. */ public Iterator<Long> getCommitTimestampsPaged(final long minTimestamp, final long maxTimestamp, final int pageSize, final int pageIndex, final Order order, final boolean includeSystemInternalCommits); /** * Returns an iterator over commit timestamps and associated metadata in a paged fashion. * * <p> * For example, calling {@code getCommitTimestampsPaged(10000, 100, 0, Order.DESCENDING)} will give the latest 100 commit timestamps that have occurred before timestamp 10000. Calling {@code getCommitTimestampsPaged(123456, 200, 2, Order.DESCENDING} will return 200 commit timestamps, skipping the 400 latest commit timestamps, which are smaller than 123456. * * <p> * The {@link Entry Entries} returned by the iterator always have the commit timestamp as their first component and the metadata associated with this commit as their second component. The second component can be <code>null</code> if the commit was executed without providing metadata. * * @param minTimestamp The minimum timestamp to consider (inclusive). All lower timestamps will be excluded from the pagination. * @param maxTimestamp The highest timestamp to consider. All higher timestamps will be excluded from the pagination. * @param pageSize The size of the page, i.e. the maximum number of elements allowed to be contained in the resulting iterator. Must be greater than zero. * @param pageIndex The index of the page to retrieve. Must not be negative. * @param order The desired ordering for the commit timestamps * @param includeSystemInternalCommits Whether or not to include system-internal commits. * @return An iterator that contains the commits for the requested page. Never <code>null</code>, may be empty. If the requested page does not exist, this iterator will always be empty. */ public Iterator<Entry<Long, Object>> getCommitMetadataPaged(final long minTimestamp, final long maxTimestamp, final int pageSize, final int pageIndex, final Order order, final boolean includeSystemInternalCommits); /** * Returns pairs of commit timestamp and commit metadata which are "around" the given timestamp on the time axis. * * <p> * By default, this method will attempt to return the closest <code>count/2</code> commits before and after the given timestamp. However, if there are not enough elements on either side, the other side will have more entries in the result list (e.g. if the request count is 10 and there are only two commits before the request timestamp, the list of commits after the request timestamp will have 8 entries instead of 5 to create a list of total length 10). In other words, the result list will always have as many entries as the request <code>count</code>, except when there are not as many commits on the store yet. * * @param timestamp The request timestamp around which the commits should be centered. Must not be negative. * @param count How many commits to retrieve around the request timestamp. By default, the closest <code>count/2</code> commits will be taken on both sides of the request timestamp. Must not be negative. * @param includeSystemInternalCommits Whether or not to include system-internal commits. * @return A list of pairs. The keys are commit timestamps, the corresponding values are the commit metadata objects (which may be <code>null</code>). The list itself will never be <code>null</code>, but may be empty (if there are no commits to report). The list is sorted in descending order by timestamps. */ public List<Entry<Long, Object>> getCommitMetadataAround(final long timestamp, final int count, final boolean includeSystemInternalCommits); /** * Returns pairs of commit timestamp and commit metadata which are strictly before the given timestamp on the time axis. * * <p> * For example, calling {@link #getCommitMetadataBefore(long, int, boolean)} with a timestamp and a count of 10, this method will return the latest 10 commits (strictly) before the given request timestamp. * * @param timestamp The timestamp to investigate. Must not be negative. * @param count How many commits to retrieve before the given request timestamp. Must not be negative. * @param includeSytemInternalCommits Whether or not to include system-internal commits. * @return A list of pairs. The keys are commit timestamps, the corresponding values are the commit metadata objects (which may be <code>null</code>). The list itself will never be <code>null</code>, but may be empty (if there are no commits to report). The list is sorted in descending order by timestamps. */ public List<Entry<Long, Object>> getCommitMetadataBefore(final long timestamp, final int count, final boolean includeSytemInternalCommits); /** * Returns pairs of commit timestamp and commit metadata which are strictly after the given timestamp on the time axis. * * <p> * For example, calling {@link #getCommitMetadataAfter(long, int, boolean)} with a timestamp and a count of 10, this method will return the oldest 10 commits (strictly) after the given request timestamp. * * @param timestamp The timestamp to investigate. Must not be negative. * @param count How many commits to retrieve after the given request timestamp. Must not be negative. * @param includeSystemInternalCommits Whether or not to include system-internal commits. * @return A list of pairs. The keys are commit timestamps, the corresponding values are the commit metadata objects (which may be <code>null</code>). The list itself will never be <code>null</code>, but may be empty (if there are no commits to report). The list is sorted in descending order by timestamps. */ public List<Entry<Long, Object>> getCommitMetadataAfter(final long timestamp, final int count, final boolean includeSystemInternalCommits); /** * Returns a list of commit timestamp which are "around" the given timestamp on the time axis. * * <p> * By default, this method will attempt to return the closest <code>count/2</code> commits before and after the given timestamp. However, if there are not enough elements on either side, the other side will have more entries in the result list (e.g. if the request count is 10 and there are only two commits before the request timestamp, the list of commits after the request timestamp will have 8 entries instead of 5 to create a list of total length 10). In other words, the result list will always have as many entries as the request <code>count</code>, except when there are not as many commits on the store yet. * * @param timestamp The request timestamp around which the commits should be centered. Must not be negative. * @param count How many commits to retrieve around the request timestamp. By default, the closest <code>count/2</code> commits will be taken on both sides of the request timestamp. Must not be negative. * @param includeSystemInternalCommits Whether or not to include system-internal commits. * @return A list of timestamps. Never be <code>null</code>, but may be empty (if there are no commits to report). The list is sorted in descending order. */ public List<Long> getCommitTimestampsAround(final long timestamp, final int count, final boolean includeSystemInternalCommits); /** * Returns a list of commit timestamps which are strictly before the given timestamp on the time axis. * * <p> * For example, calling {@link #getCommitTimestampsBefore(long, int, boolean)} with a timestamp and a count of 10, this method will return the latest 10 commits (strictly) before the given request timestamp. * * @param timestamp The timestamp to investigate. Must not be negative. * @param count How many commits to retrieve before the given request timestamp. Must not be negative. * @param includeSystemInternalCommits Whether or not to include system-internal commits. * @return A list of timestamps. Never be <code>null</code>, but may be empty (if there are no commits to report). The list is sorted in descending order. */ public List<Long> getCommitTimestampsBefore(final long timestamp, final int count, final boolean includeSystemInternalCommits); /** * Returns a list of commit timestamps which are strictly after the given timestamp on the time axis. * * <p> * For example, calling {@link #getCommitTimestampsAfter(long, int, boolean)} with a timestamp and a count of 10, this method will return the oldest 10 commits (strictly) after the given request timestamp. * * @param timestamp The timestamp to investigate. Must not be negative. * @param count How many commits to retrieve after the given request timestamp. Must not be negative. * @param includeSystemInternalCommits Whether or not to include system-internal commits. * @return A list of timestamps. Never be <code>null</code>, but may be empty (if there are no commits to report). The list is sorted in descending order. */ public List<Long> getCommitTimestampsAfter(final long timestamp, final int count, final boolean includeSystemInternalCommits); /** * Counts the number of commit timestamps between <code>from</code> (inclusive) and <code>to</code> (inclusive). * * <p> * If <code>from</code> is greater than <code>to</code>, this method will always return zero. * * @param from The minimum timestamp to include in the search (inclusive). Must not be negative. * @param to The maximum timestamp to include in the search (inclusive). Must not be negative. * @param includeSystemInternalCommits Whether or not to include system-internal commits. * @return The number of commits that have occurred in the specified time range. May be zero, but never negative. */ public int countCommitTimestampsBetween(long from, long to, final boolean includeSystemInternalCommits); /** * Counts the total number of commit timestamps in the store. * * @param includeSystemInternalCommits Whether or not to include system-internal commits. * @return The total number of commits in the store. */ public int countCommitTimestamps(final boolean includeSystemInternalCommits); /** * Puts the given commit metadata into the store and associates it with the given commit timestamp. * * @param commitTimestamp The commit timestamp to associate the metadata with. Must not be negative. * @param commitMetadata The commit metadata to associate with the timestamp. May be <code>null</code>. */ public void put(long commitTimestamp, Object commitMetadata); /** * Returns the commit metadata for the commit that occurred at the given timestamp. * * @param commitTimestamp The commit timestamp to get the metadata for. Must not be negative. * @return The commit metadata object associated with the commit at the given timestamp. May be <code>null</code> if no metadata was given for the commit. */ public Object get(long commitTimestamp); /** * Rolls back the contents of the store to the given timestamp. * * <p> * Any data associated with timestamps strictly larger than the given one will be removed from the store. * * @param timestamp The timestamp to roll back to. Must not be negative. */ public void rollbackToTimestamp(long timestamp); /** * Returns the {@link Branch} to which this store belongs. * * @return The owning branch. Never <code>null</code>. */ public Branch getOwningBranch(); /** * Purges the commit with the given timestamp from the history. * * @param commitTimestamp The timestamp of the commit to purge. Must not be negative. * @return <code>true</code> if the commit was purged successfully, or <code>false</code> if there was no commit at the given timestamp. */ public boolean purge(long commitTimestamp); /** * Checks if this store has a commit at the given timestamp. * * @param commitTimestamp The timestamp of the commit to check. Must not be negative. * @return <code>true</code> if there is a commit at the specified timestamp, otherwise <code>false</code>. */ public default boolean hasCommitAt(final long commitTimestamp) { checkArgument(commitTimestamp >= 0, "Precondition violation - argument 'commitTimestamp' must not be negative!"); Set<Long> timestamps = Sets.newHashSet(this.getCommitTimestampsBetween(commitTimestamp - 1, commitTimestamp + 1, true)); return timestamps.contains(commitTimestamp); } }
20,429
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoDBConfiguration.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/api/ChronoDBConfiguration.java
package org.chronos.chronodb.internal.api; import com.google.common.collect.Maps; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.CommitMetadataFilter; import org.chronos.chronodb.api.DuplicateVersionEliminationMode; import org.chronos.chronodb.api.conflict.ConflictResolutionStrategy; import org.chronos.chronodb.api.exceptions.ChronoDBCommitConflictException; import org.chronos.common.configuration.ChronosConfiguration; import java.io.File; /** * This class represents the configuration of a single {@link ChronoDB} instance. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API */ public interface ChronoDBConfiguration extends ChronosConfiguration { // ===================================================================================================================== // STATIC KEY NAMES // ===================================================================================================================== /** * The namespace which all settings in this configuration have in common. */ public static final String NAMESPACE = "org.chronos.chronodb"; /** * A helper constant that combines the namespace and a trailing dot (.) character. */ public static final String NS_DOT = NAMESPACE + '.'; /** * The debug setting is intended for internal use only. * * <p> * Type: boolean<br> * Default: false<br> * Maps to: {@link #isDebugModeEnabled()} */ public static final String DEBUG = NS_DOT + "debug"; /** * Whether or not to enable MBeans (JMX) integration. * * <p> * Type: boolean<br> * Default: true<br> * maps to: {@link #isMBeanIntegrationEnabled()} */ public static final String MBEANS_ENABLED = NS_DOT + "mbeans.enabled"; /** * The storage backend determines which kind of backend a {@link ChronoDB} is writing data to. * * <p> * Depending on this setting, other configuration elements may become necessary. * * <p> * Type: string<br> * Values: all literals in {@link ChronosBackend} (in their string representation)<br> * Default: none (mandatory setting)<br> * Maps to: {@link #getBackendType()} */ public static final String STORAGE_BACKEND = NS_DOT + "storage.backend"; /** * Sets the maximum size of the cache managed by the storage backend (in bytes). * * <p> * Not all storage backends support this property. * * <p> * Type: long<br> * Default: 209715200 bytes (200MB)<br> * Maps to: {@link #getStorageBackendCacheMaxSize()} */ public static final String STORAGE_BACKEND_CACHE = NS_DOT + "storage.backend.cache.maxSize"; /** * Determines if regular entry caching is enabled or not. * <p> * This allows to enable/disable caching without touching the actual {@link #CACHE_MAX_SIZE}. * * <p> * Type: boolean<br> * Default: false<br> * Maps to: {@link #isCachingEnabled()} */ public static final String CACHING_ENABLED = NS_DOT + "cache.enabled"; /** * The maximum number of elements in the entry cache. * * <p> * Type: int<br> * Default: none; needs to be assiged if {@link #CACHING_ENABLED} is set to <code>true</code>.<br> * Maps to: {@link #getCacheMaxSize()} */ public static final String CACHE_MAX_SIZE = NS_DOT + "cache.maxSize"; /** * The type of cache to deploy. * * <p> * Type: [mosaic,headFirst]<br> * Default: mosaic; * Maps to: {@link #getCacheType()} */ public static final String CACHE_TYPE = NS_DOT + "cache.type"; /** * The branch to prefer to keep in case of cache eviction. Only relevant if {@link #CACHE_TYPE} is set to headFirst. * * <p> * Type: String<br> * Default: null; * Maps to: {@link #getCacheHeadFirstPreferredBranch()} */ public static final String CACHE_HEADFIRST_PREFERRED_BRANCH = NS_DOT + "cache.headfirst.preferredBranch"; /** * The keyspace to prefer to keep in case of cache eviction. Only relevant if {@link #CACHE_TYPE} is set to headFirst. * * <p> * Type: String<br> * Default: null; * Maps to: {@link #getCacheHeadFirstPreferredKeyspace()} */ public static final String CACHE_HEADFIRST_PREFERRED_KEYSPACE = NS_DOT + "cache.headfirst.preferredKeyspace"; /** * Determines if the query cache is enabled or not. * * <p> * This allows to enable/disable the query cache without touching hte actual {@link #QUERY_CACHE_MAX_SIZE}. * * <p> * Type: boolean<br> * Default: false<br> * Maps to: {@link #isIndexQueryCachingEnabled()} */ public static final String QUERY_CACHE_ENABLED = NS_DOT + "querycache.enabled"; /** * The maximum number of query results to cache. * * <p> * Please note that the amount of RAM consumed by this cache is determined by the number of results per cached * query. Very large datasets tend to produce larger query results, which lead to increased RAM consumption while * staying at the same number of cached queries. * * <p> * Type: integer<br> * Default: 0<br> * Maps to: {@link #getIndexQueryCacheMaxSize()} */ public static final String QUERY_CACHE_MAX_SIZE = NS_DOT + "querycache.maxsize"; /** * Enables or disables the assumption that user-provided values in the entry cache are immutable. * * <p> * Setting this value to "true" will enhance the performance of the cache in terms of runtime, but may lead to data * corruption if the values returned by {@link ChronoDBTransaction#get(String) tx.get(...)} or * {@link ChronoDBTransaction#find() tx.find()} will be modified by application code. By default, this value is * therefore set to "false". * * <p> * Type: boolean<br> * Default value: false<br> * Maps to: {@link #isAssumeCachedValuesAreImmutable()} */ public static final String ASSUME_CACHE_VALUES_ARE_IMMUTABLE = NS_DOT + "cache.assumeValuesAreImmutable"; /** * Sets the {@link ConflictResolutionStrategy} to use in this database instance. * * <p> * This setting can be overruled on a by-transaction-basis. * * <p> * <b><u>/!\ WARNING /!\</u></b><br> * The values of this setting are <b>case sensitive</b>! * * <p> * Valid values for this setting are: * <ul> * <li><b>DO_NOT_RESOLVE</b>: Conflicts will not be resolved. Instead, a {@link ChronoDBCommitConflictException} * will be thrown in case of conflicts. * <li><b>OVERWRITE_WITH_SOURCE</b>: Conflicts are resolved by using the values provided by the transaction change * set. Existing conflicting values in the target branch will be overwritten. This is similar to a "force push". * <li><b>OVERWRITE_WITH_TARGET</b>: Conflicts are resolved by using the pre-existing values of conflicting keys * provided by the target branch. * <li><b>Custom Class Name</b>: Clients can provide their own implementation of the * {@link ConflictResolutionStrategy} class and specify the fully qualified class name here. ChronoDB will * instantiate this class (so it needs a visible default constructor) and use it for conflict resolution. * </ul> * * <p> * Type: String (fully qualified class name <i>or</i> one of the literals listed above)<br> * Default value: DO_NOT_RESOLVE<br> * Maps to: {@link #getConflictResolutionStrategy()} */ public static final String COMMIT_CONFLICT_RESOLUTION_STRATEGY = NS_DOT + "conflictresolver"; /** * Sets the {@link CommitMetadataFilter} to use in this database instancne. * * <p> * This setting contains the fully qualified name of the Java Class to instantiate as the filter. The given * class must exist and must have a default constructor (i.e. it must be instantiable via reflection). * * <p> * <b><u>/!\ WARNING /!\</u></b><br> * The values of this setting are <b>case sensitive</b>! * * <p> * <b><u>/!\ WARNING /!\</u></b><br> * The commit metadata filter is <b>not persisted</b> in the database. If the configuration changes, * the filter will also change on restart! * * <p> * Type: String (fully qualified class name)<br> * Default value: NULL<br> * Maps to: {@link #getCommitMetadataFilterClass()} */ public static final String COMMIT_METADATA_FILTER_CLASS = NS_DOT + "transaction.commitMetadataFilterClass"; /** * Compaction mechanism that discards a version of a key-value pair on commit if the value is identical to the * previous one. * * <p> * Duplicate versions do no "harm" to the consistency of the database, but consume memory on disk and slow down * searches without adding any information value in return. * * <p> * Duplicate version elimination does come with a performance penalty on commit (not on read). * * <p> * Type: string<br/> * Values: all literals of {@link DuplicateVersionEliminationMode} (in their string representation)<br> * Default value: "onCommit"<br/> * Maps to: {@link #getDuplicateVersionEliminationMode()} */ public static final String DUPLICATE_VERSION_ELIMINATION_MODE = NS_DOT + "temporal.duplicateVersionEliminationMode"; /** * Enables or disables performance logging for commits. * * <p> * Type: boolean<br/> * Values: <code>true</code> or <code>false</code> * Default value: "true"<br/> * Maps to: {@link #isCommitPerformanceLoggingActive()} */ public static final String PERFORMANCE_LOGGING_FOR_COMMITS = NS_DOT + ".performance.logging.commit"; /** * Sets the read-only mode for the entire {@link ChronoDB} instance. * * <p> * This parameter is always optional and <code>false</code> by default. * </p> * * <p> * Type: boolean<br> * Default value: <code>false</code><br> * Maps to: {@link #isReadOnly()} * </p> */ public static final String READONLY = NS_DOT + "readonly"; // ================================================================================================================= // GENERAL CONFIGURATION // ================================================================================================================= /** * Returns <code>true</code> if debug mode is enabled, otherwise <code>false</code>. * * <p> * Mapped by setting: {@value #DEBUG} * * @return <code>true</code> if debug mode is enabled, otherwise <code>false</code>. */ public boolean isDebugModeEnabled(); /** * Whether or not to enable MBeans (JMX) integration * * <p> * Mapped by setting: {@value #MBEANS_ENABLED} * * @return <code>true</code> if MBeans should be enabled, otherwise <code>false</code>. */ public boolean isMBeanIntegrationEnabled(); /** * Returns the type of backend this {@link ChronoDB} instance is running on. * * <p> * Mapped by setting: {@value #STORAGE_BACKEND} * * @return The backend type. Never <code>null</code>. */ public String getBackendType(); /** * Returns the maximum size of the cache maintained by the storage backend in bytes. * * <p> * Not all backends support this property and may choose to ignore this option. * * @return The maximum size of the storage backend cache in bytes. Must not be negative. */ public long getStorageBackendCacheMaxSize(); /** * Returns <code>true</code> if caching is enabled in this {@link ChronoDB} instance. * * <p> * Mapped by setting: {@value #CACHING_ENABLED} * * @return <code>true</code> if caching is enabled, otherwise <code>false</code>. */ public boolean isCachingEnabled(); /** * Returns the maximum number of elements that may reside in the cache. * * <p> * Mapped by setting: {@value #CACHE_MAX_SIZE} * * @return The maximum number of elements allowed to reside in the cache (a number greater than zero) if caching is * enabled, otherwise <code>null</code> if caching is disabled. */ public Integer getCacheMaxSize(); /** * Returns the type of cache to instantiate. * * <p> * Mapped by setting: {@value #CACHE_TYPE} * * @return The cache type to use, never null */ public CacheType getCacheType(); /** * Returns the branch to prefer to keep in case of cache eviction. * * <p> * Mapped by setting: {@value #CACHE_HEADFIRST_PREFERRED_BRANCH} * * @return The branch to keep, can be null */ public String getCacheHeadFirstPreferredBranch(); /** * Returns the keyspace to prefer to keep in case of cache eviction. * * <p> * Mapped by setting: {@value #CACHE_HEADFIRST_PREFERRED_KEYSPACE} * * @return The keyspace to keep, can be null */ public String getCacheHeadFirstPreferredKeyspace(); /** * Returns <code>true</code> when cached values may be assumed to be immutable, otherwise <code>false</code>. * * <p> * Mapped by setting: {@value #ASSUME_CACHE_VALUES_ARE_IMMUTABLE} * * @return <code>true</code> if it is safe to assume immutability of cached values, otherwise <code>false</code>. */ public boolean isAssumeCachedValuesAreImmutable(); /** * Checks if caching of index queries is allowed in this {@link ChronoDB} instance. * * <p> * Mapped by setting: {@value #QUERY_CACHE_ENABLED} * * @return <code>true</code> if caching is enabled, otherwise <code>false</code>. */ public boolean isIndexQueryCachingEnabled(); /** * Returns the maximum number of index query results to cache. * * <p> * This is only relevant if {@link #isIndexQueryCachingEnabled()} is set to <code>true</code>. * * <p> * Mapped by setting: {@value #QUERY_CACHE_MAX_SIZE} * * @return The maximum number of index query results to cache. If index query caching is disabled, this method will * return <code>null</code>. Otherwise, this method will return an integer value greater than zero. */ public Integer getIndexQueryCacheMaxSize(); /** * Returns the conflict resolution strategy that will be applied in case of commit conflicts. * * <p> * Please note that this is the <i>default</i> configuration for all transactions. This setting can be overwritten * by each individual transaction. * * @return The conflict resolution strategy. Never <code>null</code>. */ public ConflictResolutionStrategy getConflictResolutionStrategy(); /** * Returns the {@link DuplicateVersionEliminationMode} used by this {@link ChronoDB} instance. * * <p> * Mapped by setting: {@value #DUPLICATE_VERSION_ELIMINATION_MODE} * * @return The duplicate version elimination mode. Never <code>null</code>. */ public DuplicateVersionEliminationMode getDuplicateVersionEliminationMode(); /** * Returns the {@link CommitMetadataFilter} class assigned to this database instance. * * @return The commit metadata filter class. May be <code>null</code> if no filter class is set up. */ public Class<? extends CommitMetadataFilter> getCommitMetadataFilterClass(); /** * Checks if this database is to be treated as read-only. * * @return <code>true</code> if this database is read-only, otherwise <code>false</code>. */ public boolean isReadOnly(); /** * Asserts that this database is not in read-only mode. * * @throws IllegalStateException Thrown if this database is in read-only mode. */ public default void assertNotReadOnly() { if (this.isReadOnly()) { throw new IllegalStateException("Operation rejected - this database instance is read-only!"); } } /** * Returns <code>true</code> if performance logging for commits is active. * * <p> * Mapped by setting: {@value #} * * @return <code>true</code> if performance logging for commits is active, otherwise <code>false</code>. */ public boolean isCommitPerformanceLoggingActive(); }
16,640
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
TemporalDataMatrix.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/api/TemporalDataMatrix.java
package org.chronos.chronodb.internal.api; import org.chronos.chronodb.api.Order; import org.chronos.chronodb.api.key.TemporalKey; import org.chronos.chronodb.internal.api.stream.CloseableIterator; import org.chronos.chronodb.internal.impl.temporal.UnqualifiedTemporalEntry; import org.chronos.chronodb.internal.impl.temporal.UnqualifiedTemporalKey; import org.chronos.chronodb.internal.util.KeySetModifications; import java.util.*; /** * A {@link TemporalDataMatrix} is a structured container for temporal key-value pairs. * * <p> * Such a matrix is defined over a set of timestamps <i>T</i>, in combination with a set of keys <i>K</i>. A temporal * data matrix <i>D</i> is then defined as <i>D = T x K</i>. The matrix can be visualized as follows: * * <pre> * K * * ^ * | * | * +----+----+----+----+----+ * c | | V2 | | | | * +----+----+----+----+----+ * b | | | V4 | | X | * +----+----+----+----+----+ * a | V1 | | V3 | | | * +----+----+----+----+----+---> T * 1 2 3 4 5 * </pre> * <p> * In the example above, the following inserts have been applied: * <ul> * <li>a->V1 at T = 1 * <li>c->v2 at T = 2 * <li>a->v3, b-> v4 at T = 3 * <li>b->deleted at T = 5 * </ul> * <p> * Each entry in such a matrix D has a certain validity range on the T axis. For example, the entry "a->V1" is valid in * range [1;3[, while "b->V4" is valid in [3;5[. In general, each entry is valid from (including) the timestamp at which * it was inserted, up to the timestamp where the next insert occurs (exclusive). * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API */ public interface TemporalDataMatrix { // ================================================================================================================= // METADATA // ================================================================================================================= /** * Returns the name of the keyspace that is represented by this matrix. * * @return The keyspace. Never <code>null</code>. */ public String getKeyspace(); /** * Returns the timestamp at which this matrix was created. * * @return The creation timestamp. Never negative. */ public long getCreationTimestamp(); // ================================================================================================================= // QUERIES // ================================================================================================================= /** * Returns the value for the given key at the given timestamp together with the time range in which it is valid. * * @param timestamp The timestamp at which to get the value for the given key. Must not be negative. * @param key The key to get the value for. Must not be <code>null</code>. * @return A ranged result. The result object itself is guaranteed to be non-<code>null</code>. Contains the * {@linkplain GetResult#getValue() value} for the given key at the given timestamp, or contains a * <code>null</code>-{@linkplain GetResult#getValue() value} if the key does not exist in this matrix at the * given timestamp. The {@linkplain GetResult#getPeriod() range} of the returned object represents the * period in which the given key is bound to the returned value. */ public GetResult<byte[]> get(final long timestamp, final String key); /** * Returns the history of the given key, i.e. all timestamps at which the given key changed its value due to a * commit. * * @param key The key to get the commit timestamps for. Must not be <code>null</code>. * @param lowerBound The (inclusive) lower bound of the timestamp range to search in. Must not be negative. Must be less than or equal to <code>upperBound</code>. * @param upperBound The (inclusive) upper bound of the timestamp range to search in. Must not be negative. Must be greater than or equal to the <code>lowerBound</code>. * @param order The desired ordering of the result iterator. Must not be <code>null</code>. * @return An iterator over all commit timestamps on the given key, up to the given maximum timestamp. May be empty, * but never <code>null</code>. */ public Iterator<Long> history(final String key, long lowerBound, long upperBound, Order order); /** * Returns an iterator over all entries in this matrix. * * @param minTimestamp The minimum timestamp to include. Only entries with timestamps greater than or equal to this timestamp * will be considered. Must not be negative. Must be less than or equal to <code>maxTimestamp</code>. * @param maxTimestamp The maximum timestamp to include. Only entries with timestamps less than or equal to this timestamp * will be considered. Must not be negative. Must be greater than or equal to <code>minTimestamp</code>. * @return An iterator over all entries up to the given timestamp. May be empty, but never <code>null</code>. */ public CloseableIterator<UnqualifiedTemporalEntry> allEntriesIterator(long minTimestamp, long maxTimestamp); /** * Returns the timestamp at which the last (latest) commit has happened on the given key. * * @param key The key in question. Must not be <code>null</code>. * @return The latest commit timestamp, or a negative value if there has never been a commit to this key in this * matrix. */ public default long lastCommitTimestamp(String key){ return this.lastCommitTimestamp(key, System.currentTimeMillis()); } /** * Returns the last (highest) modification timestamp of the given <code>key</code> which is less than or equal to the given <code>upperBound</code>. * * @param key The key to get the last modification timestamp for. Must not be <code>null</code>. * @param upperBound The maximum change timestamp to consider (inclusive). * @return The highest modification timestamp on the given key which is less than or equal to the given upper bound, or -1 to indicate that the key has not existed up to this point. */ public long lastCommitTimestamp(String key, long upperBound); /** * Returns the {@link TemporalKey temporal keys} that were modified in the given time range. * * @param timestampLowerBound The lower bound on the timestamp to search for (inclusive). Must not be negative. Must be less than or * equal to the upper bound. * @param timestampUpperBound The upper bound on the timestamp to search for (inclusive). Must not be negative. Must be larger than * or equal to the lower bound. * @return An iterator over the temporal keys that were modified in the given time range. May be empty, but never * <code>null</code>. * @see #getCommitTimestampsBetween(long, long) */ public Iterator<TemporalKey> getModificationsBetween(long timestampLowerBound, long timestampUpperBound); /** * Returns the timestamps at which actual commits have taken place in the given time range. * * @param timestampLowerBound The lower bound on the timestamp to search for (inclusive). Must not be negative. Must be less than or * equal to the upper bound. * @param timestampUpperBound The upper bound on the timestamp to search for (inclusive). Must not be negative. Must be larger than * or equal to the lower bound. * @return An iterator over the commit timestamps in the given time range. May be empty, but never <code>null</code> * . * @see #getModificationsBetween(long, long) */ public Iterator<Long> getCommitTimestampsBetween(long timestampLowerBound, long timestampUpperBound); /** * Returns an iterator over the keys which changed their value at the given commit timestamp. * * @param commitTimestamp The commit timestamp to analyze. Must exactly match a commit timestamp in the history, otherwise the * resulting iterator will be empty. Must not be negative. * @return An iterator over the keys which changed in this matrix at the commit with the given timestamp. Never * <code>null</code>. Will be empty if there have been no changes in the given keyspace at the given commit, * if no commit has taken place at the specified timestamp, or a keyspace with the given name did not exist * at that timestamp. */ public Iterator<String> getChangedKeysAtCommit(long commitTimestamp); /** * Returns the modifications to the keyset performed in this matrix, up to the given timestamp. * * @param timestamp The timestamp for which to retrieve the modifications. Must not be negative. Must be smaller than the * timestamp of the latest change. * @return the keyset modifications. May be empty, but never <code>null</code>. */ public KeySetModifications keySetModifications(long timestamp); /** * Returns the total number of entries in this matrix. * * <p> * For chunked backends, this will return the size of the head chunk. * </p> * * @return The total number of entries. Never negative. */ public long size(); // ================================================================================================================= // CONTENT MODIFICATION // ================================================================================================================= /** * Adds the given contents to this matrix, at the given timestamp. * * @param timestamp The timestamp at which to add the given contents to this matrix. Must not be negative. * @param contents The key-value pairs to add, as a map. Must not be <code>null</code>. If the map is empty, this method * is a no-op and returns immediately. */ public void put(final long timestamp, final Map<String, byte[]> contents); /** * Inserts the given set of entries into this matrix. * * @param entries The entries to insert. Must not be <code>null</code>. If the set is empty, this method is a no-op and * returns immediately. * @param force Force the insertion of the entries, bypassing safety checks. Use <code>true</code> to force the * insertion. */ public void insertEntries(Set<UnqualifiedTemporalEntry> entries, boolean force); /** * Performs a rollback of the contents of this matrix to the given timestamp. * * <p> * Any entries which have been inserted after the given timestamp will be removed during the process. * * @param timestamp The timestamp to roll back to. Must not be negative. */ public void rollback(long timestamp); // ================================================================================================================= // DATEBACK OPERATIONS // ================================================================================================================= /** * Purges the entry at the given key and timestamp from this matrix. * * @param key The key of the entry to purge. Must not be <code>null</code>. * @param timestamp The timestamp of the entry to purge (exact match). Must not be negative. * @return <code>true</code> if the entry was purged successfully, or <code>false</code> if there was no entry to * purge at the given coordinates. */ public default boolean purgeEntry(String key, long timestamp) { return this.purgeEntries(Collections.singleton(UnqualifiedTemporalKey.create(key, timestamp))) > 0; } /** * Purges the entries at the given coordinates from this matrix. * * @param keys The keys to purge. Must not be <code>null</code>, may be empty. * @return The number of successfully purged entries. Keys which did not exist do not count towards this result. */ public int purgeEntries(Set<UnqualifiedTemporalKey> keys); /** * Purges the given key from the matrix on all timestamps. * * @param key The key to purge. Must not be <code>null</code>. * @return The timestamps at which the key was removed. May be empty, but never <code>null</code>. */ public Collection<Long> purgeKey(String key); /** * Purges all entries in the matrix that reside in the given time range, eliminating them completely from the history. * * @param purgeRangeStart The lower bound of the range to purge entries from (inclusive). Must not be negative, must not be * larger than <code>purgeRangeEnd</code>. * @param purgeRangeEnd The upper bound of the range to purge entries from (inclusive). Must not be negative, must be greater * than or equal to <code>purgeRangeStart</code>. * @return The set of coordinates which have been affected by the operation. Never <code>null</code>, may be empty. */ public Set<UnqualifiedTemporalKey> purgeAllEntriesInTimeRange(long purgeRangeStart, long purgeRangeEnd); /** * Ensures that the creation timestamp of this matrix is greater than or equal to the given value. * * <p> * If the creation timestamp of this matrix happens to be greater than the given timestamp, it will be adjusted to match it. * </p> * * @param creationTimestamp The creation timestamp to match. Must not be negative. */ public void ensureCreationTimestampIsGreaterThanOrEqualTo(long creationTimestamp); }
13,849
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
CommitTimestampProvider.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/api/CommitTimestampProvider.java
package org.chronos.chronodb.internal.api; public interface CommitTimestampProvider { public long getNextCommitTimestamp(long nowOnBranch); }
149
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
BranchManagerInternal.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/api/BranchManagerInternal.java
package org.chronos.chronodb.internal.api; import java.util.List; import java.util.Set; import org.chronos.chronodb.api.Branch; import org.chronos.chronodb.api.BranchManager; import org.chronos.chronodb.internal.impl.IBranchMetadata; /** * An extended version of the {@link BranchManager} interface. * * <p> * This interface and its methods are for internal use only, are subject to change and are not considered to be part of * the public API. Down-casting objects to internal interfaces may cause application code to become incompatible with * future releases, and is therefore strongly discouraged. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public interface BranchManagerInternal extends BranchManager { public void addBranchEventListener(BranchEventListener listener); public void removeBranchEventListener(BranchEventListener listener); @Override public BranchInternal getBranch(String branchName); /** * Loads the given branches into the system. * * <p> * It is <b>imperative</b> that the given list of branches is <b>sorted</b>. <b>Parent branches must always occur * BEFORE child branches</b> in the list! * * <p> * This method is intended for internal use only, when loading dump data. * * @param branches * The sorted list of branches, as indicated above. May be empty, but never <code>null</code>. */ public void loadBranchDataFromDump(List<IBranchMetadata> branches); public default long getMaxNowAcrossAllBranches() { return this.getBranches().stream().mapToLong(Branch::getNow).max().orElse(0); } }
1,611
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
MutableTransactionConfiguration.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/api/MutableTransactionConfiguration.java
package org.chronos.chronodb.internal.api; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.DuplicateVersionEliminationMode; import org.chronos.chronodb.api.conflict.ConflictResolutionStrategy; /** * The mutable portion of a {@link org.chronos.chronodb.api.ChronoDBTransaction.Configuration}. * <p> * * This class is not part of the public API. Down-casting a configuration to this class means leaving the public API. * * <p> * This class contains methods that are intended for building up the configuration. Once the construction is complete, * {@link #freeze()} should be called to make the configuration unmodifiable. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API */ public interface MutableTransactionConfiguration extends TransactionConfigurationInternal { /** * Sets the name of the branch on which the resulting transaction should operate. * * <p> * By default, this is set to {@link ChronoDBConstants#MASTER_BRANCH_IDENTIFIER}. * * @param branchName The branch name. Must not be <code>null</code>. */ public void setBranch(String branchName); /** * Sets the timestamp on which the resulting transaction should operate. * * <p> * By default, this is set to the "now" timestamp of the branch. To reset it to the now timestamp after calling this * method, please use {@link #setTimestampToNow()}. * * @param timestamp The timestamp. Must not be negative. */ public void setTimestamp(long timestamp); /** * Sets the timestamp on which the resulting transaction should operate to the "now" timestamp of the target branch. */ public void setTimestampToNow(); /** * Enables or disables thread-safety on this transaction. * * <p> * Important note: {@link ChronoDB} instances themselves are always thread-safe. This property only determines if * the resulting {@link ChronoDBTransaction} itself may be shared among multiple threads or not. * * @param threadSafe Set this to <code>true</code> if thread-safety on the transaction itself is required, otherwise set it * to <code>false</code> to disable thread-safety. */ public void setThreadSafe(boolean threadSafe); /** * Sets the conflict resolution strategy to apply in case of commit conflicts. * * @param strategy The strategy to use. Must not be <code>null</code>. */ public void setConflictResolutionStrategy(ConflictResolutionStrategy strategy); /** * Sets the {@link DuplicateVersionEliminationMode} on this transaction. * * @param mode The mode to use. Must not be <code>null</code>. */ public void setDuplicateVersionEliminationMode(DuplicateVersionEliminationMode mode); /** * Sets the read-only mode of this transaction configuration. * * @param readOnly Set this to <code>true</code> if the transaction should be read-only, or to <code>false</code> if it * should be read-write. */ public void setReadOnly(boolean readOnly); /** * Decides if this transaction is allowed to run during a dateback operation. * * @param allowedDuringDateback <code>true</code> if the transaction is permitted during dateback, otherwise <code>false</code>. */ public void setAllowedDuringDateback(boolean allowedDuringDateback); /** * "Freezes" the configuration. * <p> * * After calling this method, no further modifications to the transaction configuration will be allowed. */ public void freeze(); }
3,767
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoDBInternal.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/api/ChronoDBInternal.java
package org.chronos.chronodb.internal.api; import java.util.List; import org.chronos.chronodb.api.*; import org.chronos.chronodb.internal.api.index.IndexManagerInternal; import org.chronos.chronodb.internal.api.query.QueryManager; import org.chronos.chronodb.internal.api.stream.ChronoDBEntry; import org.chronos.chronodb.internal.api.stream.CloseableIterator; import org.chronos.chronodb.internal.impl.dump.CommitMetadataMap; import org.chronos.common.autolock.ReadWriteAutoLockable; import org.chronos.common.version.ChronosVersion; /** * An interface that defines methods on {@link ChronoDB} for internal use. * * <p> * If you down-cast a {@link ChronoDB} to a {@link ChronoDBInternal}, you leave the area of the public API, which is strongly discouraged! * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public interface ChronoDBInternal extends ChronoDB, ReadWriteAutoLockable { /** * Returns the internal representation of the branch manager associated with this database instance. * * @return The internal representation of the branch manager. Never <code>null</code>. */ @Override public BranchManagerInternal getBranchManager(); /** * Returns the internal representation of the dateback manager associated with this database. * * @return The internal representation of the dateback manager. Never <code>null</code>. */ @Override public DatebackManagerInternal getDatebackManager(); @Override public IndexManagerInternal getIndexManager(); /** * A method called by the {@link ChronoDBFactory} after initializing this new instance. * * <p> * This method serves as a startup hook that can be used e.g. to check if any recovery operations are necessary. */ public void postConstruct(); /** * Returns the {@link QueryManager} associated with this database instance. * * @return The query manager. Never <code>null</code>. */ public QueryManager getQueryManager(); /** * Returns the statistics manager associated with this database instance. * * @return The statistics manager. Never <code>null</code>. */ public StatisticsManagerInternal getStatisticsManager(); /** * Creates a transaction on this {@link ChronoDB} based on the given configuration. * * @param configuration * The configuration to use for transaction construction. Must not be <code>null</code>. * * @return The newly opened transaction. Never <code>null</code>. */ public ChronoDBTransaction tx(TransactionConfigurationInternal configuration); /** * Creates an iterable stream of {@link ChronoDBEntry entries} that reside in this {@link ChronoDB} instance. * * <p> * The resulting iterator will contain entries of <i>all</i> branches. * </p> * * <p> * <b>IMPORTANT:</b> The resulting stream <b>must</b> be {@linkplain CloseableIterator#close() closed} by the caller! * * <p> * Recommended usage pattern is with "try-with-resources": * * <pre> * try (ChronoDBEntryStream stream = chronoDBInternal.entryStream()) { * while (stream.hasNext()) { * ChronoDBEntry entry = stream.next(); * // do something with the entry * } * } catch (Exception e) { * // treat exception * } * </pre> * * @return The stream of entries. Never <code>null</code>, may be empty. Must be closed explicitly. */ public CloseableIterator<ChronoDBEntry> entryStream(); /** * Creates an iterable stream of {@link ChronoDBEntry entries} that reside in this {@link ChronoDB} instance. * * <p> * The resulting iterator will contain entries of <i>all</i> branches. * </p> * * <p> * <b>IMPORTANT:</b> The resulting stream <b>must</b> be {@linkplain CloseableIterator#close() closed} by the caller! * * <p> * Recommended usage pattern is with "try-with-resources": * * <pre> * try (ChronoDBEntryStream stream = chronoDBInternal.entryStream(0, 1000L)) { * while (stream.hasNext()) { * ChronoDBEntry entry = stream.next(); * // do something with the entry * } * } catch (Exception e) { * // treat exception * } * </pre> * * @param minTimestamp The minimum timestamp to consider (inclusive). Must not be negative. Must be less than <code>maxTimestamp</code>. * @param maxTimestamp The maximum timestamp to consider (inclusive). Must not be negative. Must be greater than <code>minTimestamp</code>. * * @return The stream of entries. Never <code>null</code>, may be empty. Must be closed explicitly. */ public CloseableIterator<ChronoDBEntry> entryStream(long minTimestamp, long maxTimestamp); /** * Creates an iterable stream of {@link ChronoDBEntry entries} that reside in this {@link ChronoDB} instance. * * <p> * <b>IMPORTANT:</b> The resulting stream <b>must</b> be {@linkplain CloseableIterator#close() closed} by the caller! * * <p> * Recommended usage pattern is with "try-with-resources": * * <pre> * try (ChronoDBEntryStream stream = chronoDBInternal.entryStream("master", 0, 1000L)) { * while (stream.hasNext()) { * ChronoDBEntry entry = stream.next(); * // do something with the entry * } * } catch (Exception e) { * // treat exception * } * </pre> * * @param branch The name of the branch to stream entries from. Must not be <code>null</code>. Must refer to an existing branch. * @param minTimestamp The minimum timestamp to consider (inclusive). Must not be negative. Must be less than <code>maxTimestamp</code>. * @param maxTimestamp The maximum timestamp to consider (inclusive). Must not be negative. Must be greater than <code>minTimestamp</code>. * * @return The stream of entries. Never <code>null</code>, may be empty. Must be closed explicitly. */ public CloseableIterator<ChronoDBEntry> entryStream(String branch, long minTimestamp, long maxTimestamp); /** * Loads the given list of entries into this {@link ChronoDB} instance. * * <p> * Please note that it is assumed that the corresponding branches already exist in the system. This method performs no locking on its own! * * @param entries * The entries to load. Must not be <code>null</code>, may be empty. */ public void loadEntries(List<ChronoDBEntry> entries); /** * Loads the given commit metadata into this {@link ChronoDB} instance. * * @param commitMetadata * The commit metadata to read. Must not be <code>null</code>. */ public void loadCommitTimestamps(CommitMetadataMap commitMetadata); /** * Updates the internally stored chronos version to the given version. * * @param chronosVersion * The new chronos version to store in the DB. Must not be <code>null</code>. * * @since 0.6.0 */ public void updateChronosVersionTo(ChronosVersion chronosVersion); /** * Returns the {@link CommitMetadataFilter} instance associated with this database, if any. * * @return The commit metadata filter if present, otherwise <code>null</code>. */ public CommitMetadataFilter getCommitMetadataFilter(); /** * Decides whether or not an auto-reindex after reading a DB dump is required or not. * * @return <code>true</code> if an auto-reindex should be performed after reading a dump, otherwise <code>false</code>. */ public boolean requiresAutoReindexAfterDumpRead(); /** * Returns the commit timestamp provider of this database. * * @return The commit timestamp provider. */ public CommitTimestampProvider getCommitTimestampProvider(); }
7,468
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
TemporalKeyValueStore.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/api/TemporalKeyValueStore.java
package org.chronos.chronodb.internal.api; import org.chronos.chronodb.api.Branch; import org.chronos.chronodb.api.BranchHeadStatistics; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.Dateback; import org.chronos.chronodb.api.Dateback.KeyspaceValueTransformation; import org.chronos.chronodb.api.Order; import org.chronos.chronodb.api.SerializationManager; import org.chronos.chronodb.api.TransactionSource; import org.chronos.chronodb.api.exceptions.ChronoDBCommitException; import org.chronos.chronodb.api.exceptions.DatebackException; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.api.key.TemporalKey; import org.chronos.chronodb.internal.api.stream.ChronoDBEntry; import org.chronos.chronodb.internal.api.stream.CloseableIterator; import org.chronos.common.autolock.AutoLock; import org.chronos.common.autolock.ReadWriteAutoLockable; import java.util.*; import java.util.Map.Entry; import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.Consumer; import java.util.function.Function; /** * A {@link TemporalKeyValueStore} (or <i>TKVS</i>) is a collection of named keyspaces, which in turn contain temporal * key-value pairs. * * <p> * By default, each non-empty keyspace is associated with a {@link TemporalDataMatrix} which performs the actual * operations. This class serves as a manager object that forwards the incoming requests to the correct matrix, based * upon the keyspace name. * * <p> * This class also manages the metadata of a TKVS, in particular the name of the branch to which this TKVS corresponds, * the <i>now</i> timestamp, and the index manager used by this TKVS. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API */ public interface TemporalKeyValueStore extends TransactionSource, ReadWriteAutoLockable { // ================================================================================================================= // RECOVERY // ================================================================================================================= /** * This method performs recovery operations on this store in case that it was not properly shut down last time. * * <p> * If the last shutdown was a regular shutdown, this method will only perform some quick checks and then return. If * the last shutdown occurred unexpectedly (e.g. during a commit), a recovery operation will be executed. */ public void performStartupRecoveryIfRequired(); // ================================================================================================================= // METADATA // ================================================================================================================= /** * Returns the {@link ChronoDB} instance which owns this store. * * @return The owning database. Never <code>null</code>. */ public ChronoDBInternal getOwningDB(); /** * Returns the <i>now</i> timestamp. * * <p> * The point in time we refer to as <i>now</i> is defined as the <i>last</i> timestamp where a successful commit on * this store (in any keyspace) has taken place. Therefore, <i>now</i> is always less than (or equal to) * {@link System#currentTimeMillis()}. It is a logical point in time which does not necessarily correspond to the * current wall clock time. * * <p> * In general, transactions are <b>not allowed to be opened after the <i>now</i> timestamp</b> in order to prevent * temporal anomalies. * * @return The <i>now</i> timestamp, i.e. the timestamp of the last successful commit on this store. Never negative. */ public long getNow(); /** * Returns the set of known keyspace names which are contained in this store. * * <p> * The returned set represents the known keyspaces at the given point in time. The set itself is immutable. Calling * this operation on different timestamps will produce different sets. * * @param tx The transaction to operate on. Must not be <code>null</code>. * @return An immutable set, containing the names of all keyspaces contained in this store. */ public Set<String> getKeyspaces(ChronoDBTransaction tx); /** * Returns the set of known keyspace names which are contained in this store at the given point in time. * * <p> * The returned set represents the known keyspaces at the given point in time. The set itself is immutable. Calling * this operation on different timestamps will produce different sets. * * @param timestamp The timestamp to operate on. Must not be negative. * @return An immutable set, containing the names of all keyspaces contained in this store. */ public Set<String> getKeyspaces(long timestamp); /** * Returns the {@link Branch} to which this key-value store belongs. * * @return The owning branch. Never <code>null</code>. */ public Branch getOwningBranch(); /** * Returns the {@link CommitMetadataStore} to work with in this store. * * @return The commit metadata store associated with this store. Never <code>null</code>. */ public CommitMetadataStore getCommitMetadataStore(); // ===================================================================================================================== // TRANSACTION BUILDING // ===================================================================================================================== public ChronoDBTransaction tx(TransactionConfigurationInternal configuration); /** * Opens a transaction for internal use. * * <p> * This transaction has significantly fewer preconditions and safety checks for the sake of greater flexibility. * * @param branchName The branch to operate on. Must not be <code>null</code>, must refer to an existing branch. * @param timestamp The timestamp to operate on. Must not be negative. * @return The new internal transaction. Never <code>null</code>. */ public ChronoDBTransaction txInternal(String branchName, long timestamp); // ================================================================================================================= // TRANSACTION OPERATION EXECUTION // ================================================================================================================= /** * Performs the actual commit operation for the given transaction on this store. * * <p> * During this process, the change set (see: {@link ChronoDBTransaction#getChangeSet()}) will be written to the * actual backing data store, abiding the ACID rules. * * @param tx The transaction to commit. Must not be <code>null</code>. * @param commitMetadata The metadata object to store alongside the commit. May be <code>null</code>. Will be serialized using * the {@link SerializationManager} associated with this {@link ChronoDB} instance. */ public long performCommit(ChronoDBTransaction tx, Object commitMetadata); /** * Performs an incremental commit, using the given transaction. * * <p> * For more details on the incremental commit process, please see {@link ChronoDBTransaction#commitIncremental()}. * * @param tx The transaction to perform the incremental commit for. Must not be <code>null</code>. * @return The new timestamp for the given transaction. * @throws ChronoDBCommitException Thrown if the incremental commit fails. If this exception is thrown, any changes made by the * incremental commit process will have been rolled back. */ public long performCommitIncremental(ChronoDBTransaction tx) throws ChronoDBCommitException; /** * Performs a rollback on an inremental commit process started by the given transaction. * * <p> * This operation will cancel the incremental commit process and roll back the data store to the state it has been * in before the incremental commit started. * * @param tx The transaction that started the incremental commit to roll back. Must not be <code>null</code>. */ public void performIncrementalRollback(ChronoDBTransaction tx); /** * Performs an actual <code>get</code> operation on this key-value store, in the given transaction. * * <p> * A <code>get</code> operation finds the key-value entry <code>E</code> for a given {@link QualifiedKey} * <code>K</code> where: * <ul> * <li>The keyspace and key in <code>K</code> are equal to the ones in <code>E</code> * <li>The timestamp of <code>E</code> is the largest timestamps among all entries that match the other condition, * and is less than or equal to the timestamp of the transaction * </ul> * * <p> * ... in other words, this method finds the result of the <i>latest</i> commit operation on the given key, up to * (and including) the timestamp which is specified by {@link ChronoDBTransaction#getTimestamp()}. * * @param tx The transaction in which this operation takes place. Must not be <code>null</code>. * @param key The qualified key to look up in the store. Must not be <code>null</code>. * @return The value for the key in this store at the timestamp specified by the transaction. May be * <code>null</code> to indicate that either this key was never written, was not yet written at the given * time, or has been removed (and not been re-added) before the given time. */ public Object performGet(ChronoDBTransaction tx, QualifiedKey key); /** * Performs an actual <code>get</code> operation on this key-value store, in the given transaction. * * <p> * This method is identical to {@link #performGet(ChronoDBTransaction, QualifiedKey)}, except that the binary * (non-deserialized) representation of the value is returned. * </p> * * * @param tx The transaction in which this operation takes place. Must not be <code>null</code>. * @param key The qualified key to look up in the store. Must not be <code>null</code>. * @return The value for the key in this store at the timestamp specified by the transaction, in binary format. May be * <code>null</code> to indicate that either this key was never written, was not yet written at the given * time, or has been removed (and not been re-added) before the given time. */ public byte[] performGetBinary(ChronoDBTransaction tx, QualifiedKey key); /** * This operation is equivalent to {@link #performGet(ChronoDBTransaction, QualifiedKey)}, but produces additional * result data. * * <p> * A regular <code>get</code> operation only retrieves the value which was valid in the store at the given point in * time. This method will also retrieve a {@link Period} indicating from which timestamp to which other timestamp * the returned value is valid. * * <p> * The result object of this method is essentially just a wrapper for the actual <code>get</code> result, and a * validity period. * * <p> * <b>Important note:</b> The upper bound of the validity period may <b>exceed</b> the transaction timestamp! It * reflects the actual temporal validity range of the key-value pair. This implies a number of special cases: * <ul> * <li>If a key-value pair is the latest entry for a given key (i.e. it has not yet been overridden by any other * commit), the value of the period's upper bound will be {@link Long#MAX_VALUE} to represent infinity. * <li>If there is no entry for a given key, the returned period will be the "eternal" period (i.e. ranging from * zero to {@link Long#MAX_VALUE}), and the result value will be <code>null</code>. * <li>If all entries for a given key are inserted after the requested timestamp, the returned period will start at * zero and end at the timestamp where the first key-value pair for the requested key was inserted. The result value * will be <code>null</code> in this case. * <li>If the last operation that occurred on the key before the requested timestamp was a remove operation, the * result value will be <code>null</code>. The period will start at the timestamp where the remove operation * occurred. If the key was written again at a later point in time, the period will be terminated at the timestamp * of that commit, otherwise the upper bound of the period will be {@link Long#MAX_VALUE}. * </ul> * * @param tx The transaction on which this operation occurs. Must not be <code>null</code>. * @param key The qualified key to search for. Must not be <code>null</code>. * @return A {@link GetResult} object, containing the actual result value and a temporal validity range as described * above. Never <code>null</code>. */ public GetResult<Object> performRangedGet(ChronoDBTransaction tx, QualifiedKey key); /** * This operation is equivalent to {@link #performGetBinary(ChronoDBTransaction, QualifiedKey)}, but produces additional * result data. * * <p> * A regular <code>get</code> operation only retrieves the value which was valid in the store at the given point in * time. This method will also retrieve a {@link Period} indicating from which timestamp to which other timestamp * the returned value is valid. * * <p> * The result object of this method is essentially just a wrapper for the actual <code>get</code> result, and a * validity period. * * <p> * <b>Important note:</b> The upper bound of the validity period may <b>exceed</b> the transaction timestamp! It * reflects the actual temporal validity range of the key-value pair. This implies a number of special cases: * <ul> * <li>If a key-value pair is the latest entry for a given key (i.e. it has not yet been overridden by any other * commit), the value of the period's upper bound will be {@link Long#MAX_VALUE} to represent infinity. * <li>If there is no entry for a given key, the returned period will be the "eternal" period (i.e. ranging from * zero to {@link Long#MAX_VALUE}), and the result value will be <code>null</code>. * <li>If all entries for a given key are inserted after the requested timestamp, the returned period will start at * zero and end at the timestamp where the first key-value pair for the requested key was inserted. The result value * will be <code>null</code> in this case. * <li>If the last operation that occurred on the key before the requested timestamp was a remove operation, the * result value will be <code>null</code>. The period will start at the timestamp where the remove operation * occurred. If the key was written again at a later point in time, the period will be terminated at the timestamp * of that commit, otherwise the upper bound of the period will be {@link Long#MAX_VALUE}. * </ul> * * @param tx The transaction on which this operation occurs. Must not be <code>null</code>. * @param key The qualified key to search for. Must not be <code>null</code>. * @return A {@link GetResult} object, containing the actual result value (in binary format) and a temporal * validity range as described above. Never <code>null</code>. */ public GetResult<byte[]> performRangedGetBinary(ChronoDBTransaction tx, QualifiedKey key); /** * Retrieves the set of keys contained in this store in the given keyspace at the given point in time. * * <p> * Please keep in mind that the key set can not only grow (as new keys are being added), but can also shrink when * keys are removed. The key set only reflects the keys which have valid (non-<code>null</code>) values at the given * point in time. * * @param tx The transaction on which this operation occurs. Must not be <code>null</code>. * @param keyspaceName The name of the keyspace to retrieve the key set for. Must not be <code>null</code>. * @return The key set of the given keyspace, at the point in time determined by the given transaction. May be * empty, but never <code>null</code>. If the given keyspace is unknown (i.e. does not exist yet), the empty * set will be returned. */ public Set<String> performKeySet(ChronoDBTransaction tx, String keyspaceName); /** * Returns the history of the given key in this store, within the given timestamp bounds. * * <p> * The history is represented by a number of timestamps. At each of these timestamps, a successful commit operation * has modified the value for the given key (and possibly also other key-value pairs). * * <p> * The result of this operation is an iterator which iterates over the change timestamps in the given order. * The iterator may be empty if there are no entries in the history of the given key up to the timestamp of * the given transaction (i.e. the key is unknown up to and including the timestamp of the given transaction). * * @param tx The transaction on which this operation occurs. Must not be <code>null</code>. * @param key The key to retrieve the history (change timestamps) for. Must not be <code>null</code>. * @param lowerBound The (inclusive) lower bound of the timestamp range to search in. Must not be negative. Must be less than or equal to <code>upperBound</code>. Must be less than or equal to the transaction timestamp. * @param upperBound The (inclusive) upper bound of the timestamp range to search in. Must not be negative. Must be greaer than or equal to the <code>lowerBound</code>. Must be less than or equal to the transaction timestamp. * @param order The desired ordering of the result iterator. Must not be <code>null</code>. * @return An iterator over all change timestamps (descending order; latest changes first) up to (and including) the * timestamp of the given transaction, as specified above. May be empty, but never <code>null</code>. */ public Iterator<Long> performHistory(ChronoDBTransaction tx, QualifiedKey key, long lowerBound, long upperBound, Order order); /** * Returns the most recent (highest) timestamp at which the given key was last modified. * * <p> * Modifications which occurred at a timestamp which is than the transaction timestamp will not be considered. * </p> * * <p> * If the key has been modified exactly at the transaction timestamp, the transaction timestamp will be returned. * </p> * * <p> * If the key does not exist (yet), then -1 will be returned. * </p> * * <p> * Note that the key does not need to have a value associated with it at the transaction timestamp: if the latest operation on the key was a deletion, the timestamp of the deletion will be reported. * </p> * * @param tx The transaction on which this operation occurs. Must not be <code>null</code>. * @param key The key to get the last modification timestamp for. Must not be <code>null</code>. * @return The latest timestamp at which the value associated with the given key was modified which is less than or equal to the transaction timestamp, or -1 if the key does not exist (yet). */ public long performGetLastModificationTimestamp(ChronoDBTransaction tx, QualifiedKey key); /** * Returns an iterator over the modified keys in the given timestamp range. * * <p> * Please note that <code>timestampLowerBound</code> and <code>timestampUpperBound</code> must not be larger than * the timestamp of the transaction, i.e. you can only look for timestamp ranges in the past with this method. * * @param tx The transaction to work with. Must not be <code>null</code>. * @param keyspace The keyspace to look for changes in. Must not be <code>null</code>. For non-existing keyspaces, the * resulting iterator will be empty. * @param timestampLowerBound The lower bound on the time range to look for. Must not be negative. Must be less than or equal to * <code>timestampUpperBound</code>. Must be less than or equal to the timestamp of this transaction. * @param timestampUpperBound The upper bound on the time range to look for. Must not be negative. Must be greater than or equal to * <code>timestampLowerBound</code>. Must be less than or equal to the timestamp of this transaction. * @return An iterator containing the {@link TemporalKey}s that reflect the modifications. May be empty, but never * <code>null</code>. */ public Iterator<TemporalKey> performGetModificationsInKeyspaceBetween(ChronoDBTransaction tx, String keyspace, long timestampLowerBound, long timestampUpperBound); /** * Returns the metadata object stored alongside the commit at the given timestamp. * * <p> * It is important that the given timestamp matches the commit timestamp <b>exactly</b>. * * @param tx The transaction to work with. Must not be <code>null</code>. * @param commitTimestamp The commit timestamp to get the metadata object for. Must match the commit timestamp exactly. Must not * be negative. Must be less than or equal to the timestamp of this transaction (i.e. must be in the * past). * @return The object stored alongside that commit. Will be <code>null</code> for all timestamps that are not * associated with a commit. May also be <code>null</code> in cases where no metadata object was given for * the commit by the user. */ public Object performGetCommitMetadata(ChronoDBTransaction tx, long commitTimestamp); /** * Returns an iterator over all timestamps where commits have occurred, bounded between <code>from</code> and * <code>to</code>. * * <p> * If the <code>from</code> value is greater than the <code>to</code> value, this method always returns an empty * iterator. * * @param tx The transaction to work on. Must not be <code>null</code>. * @param from The lower bound of the time range to look for commits in (inclusive). Must not be negative. Must be * less than or equal to the timestamp of this transaction. * @param to The upper bound of the time range to look for commits in (inclusive). Must not be negative. Must be * less than or equal to the timestamp of this transaction. * @param order The order of the returned timestamps. Must not be <code>null</code>. * @param includeSystemInternalCommits Whether or not to include system-internal commits.s * @return The iterator over the commit timestamps in the given time range. May be empty, but never * <code>null</code>. */ public Iterator<Long> performGetCommitTimestampsBetween(ChronoDBTransaction tx, long from, long to, Order order, final boolean includeSystemInternalCommits); /** * Returns an iterator over the entries of commit timestamp and associated metadata, bounded between * <code>from</code> and <code>to</code>. * * <p> * If the <code>from</code> value is greater than the <code>to</code> value, this method always returns an empty * iterator. * * <p> * Please keep in mind that some commits may not have any metadata attached. In this case, the * {@linkplain Entry#getValue() value} component of the {@link Entry} will be set to <code>null</code>. * * @param tx The transaction to work on. Must not be <code>null</code>. * @param from The lower bound of the time range to look for commits in (inclusive). Must not be negative. Must be * less than or equal to the timestamp of this transaction. * @param to The upper bound of the time range to look for commits in (inclusive). Must not be negative. Must be * less than or equal to the timestamp of this transaction. * @param order The order of the returned commits. Must not be <code>null</code>. * @param includeSystemInternalCommits Whether or not to include system-internal commits. * @return An iterator over the commits in the given time range. The contained entries have the timestamp as the * {@linkplain Entry#getKey() key} component and the associated metadata as their * {@linkplain Entry#getValue() value} component (which may be <code>null</code>). May be empty, but never * <code>null</code>. */ public Iterator<Entry<Long, Object>> performGetCommitMetadataBetween(ChronoDBTransaction tx, long from, long to, Order order, final boolean includeSystemInternalCommits); /** * Returns an iterator over commit timestamps in a paged fashion. * * <p> * For example, calling {@code getCommitTimestampsPaged(10000, 100, 0, Order.DESCENDING)} will give the latest 100 * commit timestamps that have occurred before timestamp 10000. Calling * {@code getCommitTimestampsPaged(123456, 200, 2, Order.DESCENDING} will return 200 commit timestamps, skipping the * 400 latest commit timestamps, which are smaller than 123456. * * @param tx The transaction to use. Must not be <code>null</code>. * @param minTimestamp The minimum timestamp to consider (inclusive). All lower timestamps will be excluded from the * pagination. Must be less than or equal to the timestamp of this transaction. * @param maxTimestamp The highest timestamp to consider (inclusive). All higher timestamps will be excluded from the * pagination. Must be less than or equal to the timestamp of this transaction. * @param pageSize The size of the page, i.e. the maximum number of elements allowed to be contained in the resulting * iterator. Must be greater than zero. * @param pageIndex The index of the page to retrieve. Must not be negative. * @param order The desired ordering for the commit timestamps * @param includeSystemInternalCommits Whether or not to include system-internal commits. * @return An iterator that contains the commit timestamps for the requested page. Never <code>null</code>, may be * empty. If the requested page does not exist, this iterator will always be empty. */ public Iterator<Long> performGetCommitTimestampsPaged(ChronoDBTransaction tx, final long minTimestamp, final long maxTimestamp, final int pageSize, final int pageIndex, final Order order, final boolean includeSystemInternalCommits); /** * Returns an iterator over commit timestamps and associated metadata in a paged fashion. * * <p> * For example, calling {@code getCommitTimestampsPaged(10000, 100, 0, Order.DESCENDING)} will give the latest 100 * commit timestamps that have occurred before timestamp 10000. Calling * {@code getCommitTimestampsPaged(123456, 200, 2, Order.DESCENDING} will return 200 commit timestamps, skipping the * 400 latest commit timestamps, which are smaller than 123456. * * <p> * The {@link Entry Entries} returned by the iterator always have the commit timestamp as their first component and * the metadata associated with this commit as their second component. The second component can be <code>null</code> * if the commit was executed without providing metadata. * * @param tx The transaction to work on. Must not be <code>null</code>. * @param minTimestamp The minimum timestamp to consider (inclusive). All lower timestamps will be excluded from the * pagination. Must be less than or equal to the timestamp of this transaction. * @param maxTimestamp The highest timestamp to consider. All higher timestamps will be excluded from the pagination. Must be * less than or equal to the timestamp of this transaction. * @param pageSize The size of the page, i.e. the maximum number of elements allowed to be contained in the resulting * iterator. Must be greater than zero. * @param pageIndex The index of the page to retrieve. Must not be negative. * @param order The desired ordering for the commit timestamps * @param includeSystemInternalCommits Whether or not to include system-internal commits. * @return An iterator that contains the commits for the requested page. Never <code>null</code>, may be empty. If * the requested page does not exist, this iterator will always be empty. */ public Iterator<Entry<Long, Object>> performGetCommitMetadataPaged(final ChronoDBTransaction tx, final long minTimestamp, final long maxTimestamp, final int pageSize, final int pageIndex, final Order order, final boolean includeSystemInternalCommits); /** * Returns pairs of commit timestamp and commit metadata which are "around" the given timestamp on the time axis. * * <p> * By default, this method will attempt to return the closest <code>count/2</code> commits before and after the * given timestamp. However, if there are not enough elements on either side, the other side will have more entries * in the result list (e.g. if the request count is 10 and there are only two commits before the request timestamp, * the list of commits after the request timestamp will have 8 entries instead of 5 to create a list of total length * 10). In other words, the result list will always have as many entries as the request <code>count</code>, except * when there are not as many commits on the store yet. * * @param timestamp The request timestamp around which the commits should be centered. Must not be negative. * @param count How many commits to retrieve around the request timestamp. By default, the closest * <code>count/2</code> commits will be taken on both sides of the request timestamp. Must not be * negative. * @param includeSystemInternalCommits Whether or not to include system-internal commits. * @return A list of pairs. The keys are commit timestamps, the corresponding values are the commit metadata objects * (which may be <code>null</code>). The list itself will never be <code>null</code>, but may be empty (if * there are no commits to report). The list is sorted in descending order by timestamp. */ public List<Entry<Long, Object>> performGetCommitMetadataAround(long timestamp, int count, final boolean includeSystemInternalCommits); /** * Returns pairs of commit timestamp and commit metadata which are strictly before the given timestamp on the time * axis. * * <p> * For example, calling {@link #performGetCommitMetadataBefore(long, int, boolean)} with a timestamp and a count of 10, this * method will return the latest 10 commits (strictly) before the given request timestamp. * * @param timestamp The timestamp to investigate. Must not be negative. * @param count How many commits to retrieve before the given request timestamp. Must not be negative. * @param includeSytemInternalCommits Whether or not to include system-internal commits. * @return A list of pairs. The keys are commit timestamps, the corresponding values are the commit metadata objects * (which may be <code>null</code>). The list itself will never be <code>null</code>, but may be empty (if * there are no commits to report). The list is sorted in descending order by timestamp. */ public List<Entry<Long, Object>> performGetCommitMetadataBefore(long timestamp, int count, final boolean includeSytemInternalCommits); /** * Returns pairs of commit timestamp and commit metadata which are strictly after the given timestamp on the time * axis. * * <p> * For example, calling {@link #performGetCommitMetadataAfter(long, int, boolean)} with a timestamp and a count of 10, this * method will return the oldest 10 commits (strictly) after the given request timestamp. * * @param timestamp The timestamp to investigate. Must not be negative. * @param count How many commits to retrieve after the given request timestamp. Must not be negative. * @param includeSystemInternalCommits Whether or not to include system-internal commits. * @return A list of pairs. The keys are commit timestamps, the corresponding values are the commit metadata objects * (which may be <code>null</code>). The list itself will never be <code>null</code>, but may be empty (if * there are no commits to report). The list is sorted in descending order by timestamp. */ public List<Entry<Long, Object>> performGetCommitMetadataAfter(long timestamp, int count, final boolean includeSystemInternalCommits); /** * Returns a list of commit timestamp which are "around" the given timestamp on the time axis. * * <p> * By default, this method will attempt to return the closest <code>count/2</code> commits before and after the * given timestamp. However, if there are not enough elements on either side, the other side will have more entries * in the result list (e.g. if the request count is 10 and there are only two commits before the request timestamp, * the list of commits after the request timestamp will have 8 entries instead of 5 to create a list of total length * 10). In other words, the result list will always have as many entries as the request <code>count</code>, except * when there are not as many commits on the store yet. * * @param timestamp The request timestamp around which the commits should be centered. Must not be negative. * @param count How many commits to retrieve around the request timestamp. By default, the closest * <code>count/2</code> commits will be taken on both sides of the request timestamp. Must not be * negative. * @param includeSystemInternalCommits Whether or not to include system-internal commits. * @return A list of timestamps. Never be <code>null</code>, but may be empty (if there are no commits to report). * The list is sorted in descending order. */ public List<Long> performGetCommitTimestampsAround(long timestamp, int count, final boolean includeSystemInternalCommits); /** * Returns a list of commit timestamps which are strictly before the given timestamp on the time axis. * * <p> * For example, calling {@link #performGetCommitTimestampsBefore(long, int, boolean)} with a timestamp and a count of 10, * this method will return the latest 10 commits (strictly) before the given request timestamp. * * @param timestamp The timestamp to investigate. Must not be negative. * @param count How many commits to retrieve before the given request timestamp. Must not be negative. * @param includeSystemInternalCommits Whether or not to include system-internal commits. * @return A list of timestamps. Never be <code>null</code>, but may be empty (if there are no commits to report). * The list is sorted in descending order. */ public List<Long> performGetCommitTimestampsBefore(long timestamp, int count, final boolean includeSystemInternalCommits); /** * Returns a list of commit timestamps which are strictly after the given timestamp on the time axis. * * <p> * For example, calling {@link #performGetCommitTimestampsAfter(long, int, boolean)} with a timestamp and a count of 10, this * method will return the oldest 10 commits (strictly) after the given request timestamp. * * @param timestamp The timestamp to investigate. Must not be negative. * @param count How many commits to retrieve after the given request timestamp. Must not be negative. * @param includeSystemInternalCommits Whether or not to include system-internal commits. * @return A list of timestamps. Never be <code>null</code>, but may be empty (if there are no commits to report). * The list is sorted in descending order. */ public List<Long> performGetCommitTimestampsAfter(long timestamp, int count, final boolean includeSystemInternalCommits); /** * Counts the number of commit timestamps between <code>from</code> (inclusive) and <code>to</code> (inclusive). * * <p> * If <code>from</code> is greater than <code>to</code>, this method will always return zero. * * @param tx The transaction to work on. Must not be <code>null</code>. * @param from The minimum timestamp to include in the search (inclusive). Must not be negative. Must be less than or * equal to the timestamp of this transaction. * @param to The maximum timestamp to include in the search (inclusive). Must not be negative. Must be less than or * equal to the timestamp of this transaction. * @param includeSystemInternalCommits Whether or not to include system-internal commits. * @return The number of commits that have occurred in the specified time range. May be zero, but never negative. */ public int performCountCommitTimestampsBetween(ChronoDBTransaction tx, long from, long to, final boolean includeSystemInternalCommits); /** * Counts the total number of commit timestamps in the store. * * @param tx The transaction to work on. Must not be <code>null</code>. * @param includeSystemInternalCommits Whether or not to include system-internal commits. * @return The total number of commits in the store. */ public int performCountCommitTimestamps(ChronoDBTransaction tx, final boolean includeSystemInternalCommits); /** * Returns an iterator over the keys which changed their value at the given commit timestamp. * * @param tx The transaction to work on. Must not be <code>null</code>. * @param commitTimestamp The commit timestamp to analyze. Must exactly match a commit timestamp in the history, otherwise the * resulting iterator will be empty. Use one of the commit timestamp retrieval methods to find the commit * timestamps (e.g. {@link #performGetCommitTimestampsBetween(ChronoDBTransaction, long, long, Order, boolean)}). Must not be negative. Must not be * larger than the timestamp of this transaction. * @param keyspace The keyspace to scan for changes. Must not be <code>null</code>. * @return An iterator over the keys which changed in the given keyspace at the commit with the given timestamp. * Never <code>null</code>. Will be empty if there have been no changes in the given keyspace at the given * commit, if no commit has taken place at the specified timestamp, or a keyspace with the given name did * not exist at that timestamp. */ public Iterator<String> performGetChangedKeysAtCommit(ChronoDBTransaction tx, long commitTimestamp, String keyspace); // ================================================================================================================= // DATEBACK API // ================================================================================================================= /** * Purges the entry at the given coordinates from the store, eliminating it completely from the history. * * @param keyspace The keyspace of the entry to purge. Must not be <code>null</code>. * @param key The key of the entry to purge. Must not be <code>null</code>. * @param timestamp The (exact) timestamp of the entry to purge. Must not be negative. * @return <code>true</code> if the entry was purged successfully, or <code>false</code> if the entry did not exist. */ public default boolean datebackPurgeEntry(String keyspace, String key, long timestamp){ return this.datebackPurgeEntries(Collections.singleton(TemporalKey.create(timestamp, keyspace, key))) > 0; } /** * Purges the entries at the given coordinates from the store, eliminating them completely from the history. * * @param keys The keys of the entries to purge. * @return the number of entries which have been purged successfully. If an entry did not exist, it will not count towards this number. */ public int datebackPurgeEntries(Set<TemporalKey> keys); /** * Purges the given key from the store, eliminating it completely from the history. * * <p> * In contrast to {@link #datebackPurgeEntry(String, String, long)}, this method will remove ALL occurrences of the * key. In other words, after calling this method, the history of the key will be empty. * * @param keyspace The keyspace in which the key resides. Must not be <code>null</code>. * @param key The key to (unconditionally) purge from the store. Must not be <code>null</code>. * @return The set of affected coordinates. Never <code>null</code>. May be empty if the key did not exist in the * store. */ public Set<TemporalKey> datebackPurgeKey(String keyspace, String key); /** * Purges all entries with the given key from the store which match the given predicate, eliminating them completely * from the history. * * <p> * In contrast to {@link #datebackPurgeEntry(String, String, long)}, this method can potentially remove multiple * occurrences of the key. * * @param keyspace The keyspace where the key resides. Must not be <code>null</code>. * @param key The key to purge from the store. Must not be <code>null</code>. * @param predicate The predicate to use for deciding whether to purge an entry or not. Must not be <code>null</code>. * Must be a pure, side-effect free function. The first parameter is the timestamp of the entry at hand, * the second parameter is the value associated with the key at this timestamp (which may be * <code>null</code> to indicate that this entry is a deletion). The function should return * <code>true</code> if the entry should be purged, or <code>false</code> if the entry should remain * untouched. * @return The set of coordinates which have been affected by the operation. Never <code>null</code>. May be empty * if no coordinates were affected. */ public Set<TemporalKey> datebackPurgeKey(String keyspace, String key, BiPredicate<Long, Object> predicate); /** * Purges all entries with the given key from the store that reside in the given time range, eliminating them * completely from the history. * * @param keyspace The keyspace where the key resides. Must not be <code>null</code>. * @param key The key to purge from the store. Must not be <code>null</code>. * @param purgeRangeStart The lower bound of the range to purge entries from (inclusive). Must not be negative, must not be * larger than <code>purgeRangeEnd</code>. * @param purgeRangeEnd The upper bound of the range to purge entries from (inclusive). Must not be negative, must be greater * than or equal to <code>purgeRangeStart</code>. * @return The set of coordinates which have been affected by the operation. Never <code>null</code>. May be empty * if no coordinates were affected. */ public Set<TemporalKey> datebackPurgeKey(String keyspace, String key, long purgeRangeStart, long purgeRangeEnd); /** * Purges all entries in the given keyspace that reside in the given time range, eliminating them completely from the history. * * @param keyspace The keyspace to purge the entries from. Must not be <code>null</code>. * @param purgeRangeStart The lower bound of the range to purge entries from (inclusive). Must not be negative, must not be * larger than <code>purgeRangeEnd</code>. * @param purgeRangeEnd The upper bound of the range to purge entries from (inclusive). Must not be negative, must be greater * than or equal to <code>purgeRangeStart</code>. * @return The set of coordinates which have been affected by the operation. Never <code>null</code>, may be empty. */ public Set<TemporalKey> datebackPurgeKeyspace(final String keyspace, final long purgeRangeStart, final long purgeRangeEnd); /** * Purges the given commit from the store, eliminating it (and its associated changes) completely from the history. * * <p> * This will also delete the commit metadata associated with the commit. * * @param commitTimestamp The (exact) timestamp of the commit to purge. Must not be negative. * @return The set of coordinates which have been affected by the operation. Never <code>null</code>. May be empty * if no coordinates were affected. */ public Set<TemporalKey> datebackPurgeCommit(long commitTimestamp); /** * Purges all commits in the given time range (and their associated changes and metadata), eliminating them * completely from the store. * * @param purgeRangeStart The lower bound of the timestamp range to perform the purging in (inclusive). Must not be negative, * must not be larger than <code>purgeRangeEnd</code>. * @param purgeRangeEnd The upper bound of the timestamp range to perform the purging in (inclusive). Must not be negative, * must not be smaller than <code>purgeRangeStart</code>. * @return The set of coordinates which have been affected by the operation. Never <code>null</code>. May be empty * if no coordinates were affected. */ public Set<TemporalKey> datebackPurgeCommits(long purgeRangeStart, long purgeRangeEnd); /** * Injects an entry with the given properties into the store. * * <p> * Please keep in mind the following properties of this operation: * <ul> * <li>If an entry existed at the specified coordinates, this entry will be <b>overwritten</b>. * <li>Using <code>null</code> as the <code>value</code> parameter inserts a "deletion" entry. * <li>This method can potentially introduce a new commit in the commit log. * <li>This method can <b>not</b> be used to inject entries in the future. * <li>This method can <b>not</b> be used to inject entries historically before the branching timestamp of the * current branch. * <li>This method <b>can</b> be used to create new keyspaces by specifying a previously unused keyspace name. * <li>This method <b>can</b> be used to inject entries after the current "now" timestamp, but not after * {@link System#currentTimeMillis()}. Injecting entries after "now" will advance the "now" timestamp. * </ul> * * @param keyspace The keyspace in which the new entry should be created. Must not be <code>null</code>. If the keyspace * did not exist before, it will be created. * @param key The key at which the new entry should be created. Must not be <code>null</code>. * @param timestamp The timestamp at which the new entry should be inserted. Any existing entry at this timestamp will be * overwritten. Must not be negative. Must be larger than the branching timestamp of this branch. Must * not be in the future. * @param value The value to insert. May be <code>null</code> to indicate that the key was deleted from the store at * these coordinates. * @return The set of coordinates which have been affected by the operation. Never <code>null</code>. */ public Set<TemporalKey> datebackInject(String keyspace, String key, long timestamp, Object value); /** * Injects an entry with the given properties into the store. * * <p> * Please keep in mind the following properties of this operation: * <ul> * <li>If an entry existed at the specified coordinates, this entry will be <b>overwritten</b>. * <li>Using <code>null</code> as the <code>value</code> parameter inserts a "deletion" entry. * <li>This method can potentially introduce a new commit in the commit log. * <li>This method can <b>not</b> be used to inject entries in the future. * <li>This method can <b>not</b> be used to inject entries historically before the branching timestamp of the * current branch. * <li>This method <b>can</b> be used to create new keyspaces by specifying a previously unused keyspace name. * <li>This method <b>can</b> be used to inject entries after the current "now" timestamp, but not after * {@link System#currentTimeMillis()}. Injecting entries after "now" will advance the "now" timestamp. * </ul> * * @param keyspace The keyspace in which the new entry should be created. Must not be <code>null</code>. If the keyspace * did not exist before, it will be created. * @param key The key at which the new entry should be created. Must not be <code>null</code>. * @param timestamp The timestamp at which the new entry should be inserted. Any existing entry at this timestamp will be * overwritten. Must not be negative. Must be larger than the branching timestamp of this branch. Must * not be in the future. * @param value The value to insert. May be <code>null</code> to indicate that the key was deleted from the store at * these coordinates. * @param commitMetadata The commit metadata to use for the entry. Will override pre-existing commit metadata, in case that * there was a commit at the given timestamp. May be <code>null</code>. * @return The set of coordinates which have been affected by the operation. Never <code>null</code>. */ public Set<TemporalKey> datebackInject(String keyspace, String key, long timestamp, Object value, Object commitMetadata); /** * Injects an entry with the given properties into the store. * * <p> * Please keep in mind the following properties of this operation: * <ul> * <li>If an entry existed at the specified coordinates, this entry will be <b>overwritten</b>. * <li>Using <code>null</code> as the <code>value</code> parameter inserts a "deletion" entry. * <li>This method can potentially introduce a new commit in the commit log. * <li>This method can <b>not</b> be used to inject entries in the future. * <li>This method can <b>not</b> be used to inject entries historically before the branching timestamp of the * current branch. * <li>This method <b>can</b> be used to create new keyspaces by specifying a previously unused keyspace name. * <li>This method <b>can</b> be used to inject entries after the current "now" timestamp, but not after * {@link System#currentTimeMillis()}. Injecting entries after "now" will advance the "now" timestamp. * </ul> * * @param keyspace The keyspace in which the new entry should be created. Must not be <code>null</code>. If the keyspace * did not exist before, it will be created. * @param key The key at which the new entry should be created. Must not be <code>null</code>. * @param timestamp The timestamp at which the new entry should be inserted. Any existing entry at this timestamp will be * overwritten. Must not be negative. Must be larger than the branching timestamp of this branch. Must * not be in the future. * @param value The value to insert. May be <code>null</code> to indicate that the key was deleted from the store at * these coordinates. * @param commitMetadata The commit metadata to use for the entry. May be <code>null</code>. * @param overrideCommitMetadata Decides whether or not to override pre-existing commit metadata (if there is a commit at the given * timestamp). Use <code>true</code> to override existing metadata, or <code>false</code> to keep it * intact if it exists. If no commit metadata exists at the given timestamp, this parameter will be * ignored. * @return The set of coordinates which have been affected by the operation. Never <code>null</code>. */ public Set<TemporalKey> datebackInject(String keyspace, String key, long timestamp, Object value, Object commitMetadata, boolean overrideCommitMetadata); /** * Injects multiple entries at the given timestamp into the store. * * <p> * This is a multiplicity-many version of {@link #datebackInject(String, String, long, Object)}; the same * restrictions regarding the entries apply here. * * @param timestamp The timestamp at which to inject the entries. Must not be negative. Must be greater than the branching * timestamp of the current branch. Must not be in the future. * @param entries The entries to insert at the given timestamp. The map entries contain the keyspace/key combination in * the first component and the corresponding value in the second component. <code>null</code> is a legal * entry value and can be used to indicate a deletion in the store. The map itself must not be * <code>null</code>. * @return The set of coordinates which have been affected by the operation. Never <code>null</code>. */ public Set<TemporalKey> datebackInject(long timestamp, Map<QualifiedKey, Object> entries); /** * Injects multiple entries at the given timestamp into the store. * * <p> * This is a multiplicity-many version of {@link #datebackInject(String, String, long, Object)}; the same * restrictions regarding the entries apply here. * * @param timestamp The timestamp at which to inject the entries. Must not be negative. Must be greater than the branching * timestamp of the current branch. Must not be in the future. * @param entries The entries to insert at the given timestamp. The map entries contain the keyspace/key combination in * the first component and the corresponding value in the second component. <code>null</code> is a legal * entry value and can be used to indicate a deletion in the store. The map itself must not be * <code>null</code>. * @param commitMetadata The commit metadata to store for this timestamp. This will override pre-existing metadata, if there * has been a previous commit on this timestamp. * @return The set of coordinates which have been affected by the operation. Never <code>null</code>. */ public Set<TemporalKey> datebackInject(long timestamp, Map<QualifiedKey, Object> entries, Object commitMetadata); /** * Injects multiple entries at the given timestamp into the store. * * <p> * This is a multiplicity-many version of {@link #datebackInject(String, String, long, Object)}; the same * restrictions regarding the entries apply here. * * @param timestamp The timestamp at which to inject the entries. Must not be negative. Must be greater than the branching * timestamp of the current branch. Must not be in the future. * @param entries The entries to insert at the given timestamp. The map entries contain the keyspace/key combination in * the first component and the corresponding value in the second component. <code>null</code> is a legal * entry value and can be used to indicate a deletion in the store. The map itself must not be * <code>null</code>. * @param commitMetadata The commit metadata to store for this timestamp. This will override pre-existing metadata, if there * has been a previous commit on this timestamp. * @param overrideCommitMetadata Decides whether or not to override pre-existing commit metadata (if there is a commit at the given * timestamp). Use <code>true</code> to override existing metadata, or <code>false</code> to keep it * intact if it exists. If no commit metadata exists at the given timestamp, this parameter will be * ignored. * @return The set of coordinates which have been affected by the operation. Never <code>null</code>. */ public Set<TemporalKey> datebackInject(long timestamp, Map<QualifiedKey, Object> entries, Object commitMetadata, boolean overrideCommitMetadata); /** * Transforms the entry at the given coordinates by applying the given transformation function. * * <p> * Please note that the transformation function may return the {@link Dateback#UNCHANGED} constant to indicate that * the transformation does not change the value. * * @param keyspace The keyspace of the entry to transform. Must not be <code>null</code>. * @param key The key of the entry to transform. Must not be <code>null</code>. * @param timestamp The timestamp of the entry to transform. Must match the entry <b>exactly</b>. Must not be negative. * @param transformation The transformation to apply. Must not be <code>null</code>. May return {@link Dateback#UNCHANGED} to * indicate that the value should remain unchanged. The passed value may be <code>null</code> to indicate * that the entry marks a deletion. The function has to be a pure function, i.e. free of side effects and * depending only on the passed parameters. * @return The set of temporal keys that have been altered by this operation. May be empty, but never * <code>null</code>. */ public Set<TemporalKey> datebackTransformEntry(String keyspace, String key, long timestamp, Function<Object, Object> transformation); /** * Transforms all values of the given key by applying the given transformation function. * * <p> * Please note that the transformation function may return the {@link Dateback#UNCHANGED} constant to indicate that * the transformation does not change the value. * * @param keyspace The keyspace of the entries to transform. Must not be <code>null</code>. * @param key The key of the entries to transform. Must not be <code>null</code>. * @param transformation The transformation function to apply. It receives the timestamp and the value of the entry as * parameters and should return the new value to assign to the given timestamp. The function may return * <code>null</code> in order to indicate a deletion. The passed value may be <code>null</code> to * indicate that the entry marks a deletion. The function should return {@link Dateback#UNCHANGED} to * indicate that the current entry remains unchanged. The function has to be a pure function, i.e. free * of side effects and depending only on the passed parameters. * @return The set of temporal keys that have been altered by this operation. May be empty, but never * <code>null</code>. */ public Set<TemporalKey> datebackTransformValuesOfKey(String keyspace, String key, BiFunction<Long, Object, Object> transformation); /** * Transforms all entries that belong to a given commit. * * <p> * The transformation function <b>may</b>: * <ul> * <li>Add new entries to the map. Those will be injected into the commit. * <li>Remove entries from the map. Those will be removed from the commit. * <li>Change the values associated with keys. Those will be updated. * <li>Assign the {@link Dateback#UNCHANGED} value to a key. This will leave the entry untouched in the commit. * </ul> * <p> * The map passed to the transformation function as parameter is <b>immutable</b>. The transformation function * should construct a new map internally and return it. * * @param commitTimestamp The (precise) timestamp of the commit to transform. Must not be negative. If there is no commit at the * specified timestamp, this method is a no-op and will return immediately. * @param transformation The transformation function to apply. Must not be <code>null</code>. Must be a pure, side-effect free * function. * @return The set of temporal keys that have been altered by this operation. May be empty, but never * <code>null</code>. */ public Set<TemporalKey> datebackTransformCommit(long commitTimestamp, Function<Map<QualifiedKey, Object>, Map<QualifiedKey, Object>> transformation); /** * Transforms the values of the given keyspace. * * <p> * This method <b>is allowed</b> to: * <ul> * <li>Update existing values</li> * <li>Leave existing values the same</li> * </ul> * </p> * * <p> * This method is <b>not allowed</b> to: * <ul> * <li>Replace a value with a deletion marker</li> * <li>Delete existing entries</li> * <li>Introduce new entries at coordinates which previously had no entry</li> * </ul> * * </p> * * @param keyspace The keyspace to transform. Must not be <code>null</code>. * @param valueTransformation The value transformation to apply. Must not be <code>null</code>. * * @return The coordinates which have actually been modified. */ public Collection<TemporalKey> datebackTransformValuesOfKeyspace(String keyspace, KeyspaceValueTransformation valueTransformation); /** * Updates the metadata of the given commit, replacing it with the given one. * * @param commitTimestamp The timestamp of the commit to update the metadata for. Must not be <code>null</code>, must refer to * an existing commit in the store. * @param newMetadata The new metadata object to assign to the commit. May be <code>null</code>. * @throws DatebackException Thrown if there is no commit in the store at the given timestamp. */ public void datebackUpdateCommitMetadata(long commitTimestamp, Object newMetadata); /** * Performs cleanup operations on the underlying store (if necessary). * * <p> * Users can call this operation in order to flush changes into the store and freeing RAM. * * <p> * Cleanup will also be performed automatically at the end of a dateback process. * * @param branch The branch on which the dateback operations have occurred. * @param earliestTouchedTimestamp The earliest timestamp which has been modified by a dateback operation. Must not be negative. */ public void datebackCleanup(final String branch, long earliestTouchedTimestamp); // ================================================================================================================= // BRANCH LOCKING // ================================================================================================================= /** * Declares that a thread is about to perform a non-exclusive task that can run in parallel with other non-exclusive * locking tasks. * * <p> * This method ensures that non-exclusive operations are properly blocked when an exclusive operation is taking * place. * * <p> * This method <b>also acquires the non-exclusive lock</b> on the whole database! * * <p> * This method must be used together with the <code>try-with-resources</code> pattern. See * {@link ReadWriteAutoLockable#lockNonExclusive()} for an example. * * @return The object representing the lock ownership. Never <code>null</code>. Will be closed automatically by the * <code>try-with-resources</code> statement. */ @Override public AutoLock lockNonExclusive(); /** * Declares that a thread is about to perform an exclusive task that can't run in parallel with other locking tasks. * * <p> * This method acquires the exclusive lock on the entire database! * * <p> * This method must be used together with the <code>try-with-resources</code> pattern. See * {@link ReadWriteAutoLockable#lockExclusive()} for an example. * * @return The object representing the lock ownership. Never <code>null</code>. Will be closed automatically by the * <code>try-with-resources</code> statement. */ @Override public AutoLock lockExclusive(); /** * Declares that a thread is about to perform a non-exclusive task that can run in parallel with other non-exclusive * locking tasks on this branch. * * <p> * This method <b>also acquires the non-exclusive lock</b> on the whole database! * * <p> * This method must be used together with the <code>try-with-resources</code> pattern. See * {@link ReadWriteAutoLockable#lockNonExclusive()} for an example. * * @return The object representing the lock ownership. Never <code>null</code>. Will be closed automatically by the * <code>try-with-resources</code> statement. */ public AutoLock lockBranchExclusive(); // ================================================================================================================= // DUMP UTILITY // ================================================================================================================= /** * Returns an iterator over all entries in this data store which have timestamps less than or equal to the given * timestamp. * * <p> * This method is intended primarily for operations that perform backup work on the database. It is <b>strongly * discouraged</b> to perform any kind of filtering or analysis on the returned iterator (for performance reasons); * use one of the other retrieval methods provided by this class instead. * * <p> * <b>/!\ WARNING /!\</b><br> * This method will return only entries from <b>this</b> branch! Entries from the origin branch (if any) will * <b>not</b> be included in the returned iterator! * * <p> * <b>/!\ WARNING /!\</b><br> * The resulting iterator <b>must</b> be {@linkplain CloseableIterator#close() closed} by the caller! * * @param minTimestmap The minimum timestamp to consider. Only entries with timestamps greater than or equal to this value will be returned. Must not be negative. Must be less than or equal to <code>maxTimestamp</code>. * @param maxTimestamp The maximum timestamp to consider. Only entries with timestamps less than or equal to this value will * be returned. Must not be negative. Must be greater than or equal to <code>minTimestamp</code>. * @return An iterator over all entries with timestamps less than or equal to the given timestamp. May be empty, but * never <code>null</code>. Must be closed by the caller. */ public CloseableIterator<ChronoDBEntry> allEntriesIterator(long minTimestmap, long maxTimestamp); /** * Directly inserts the given entries into this store, without performing any temporal consistency checks. * * <p> * This method is intended to be used only for loading a previously stored backup, and is <b>strongly * discouraged</b> for regular use. Please use transactions and commits instead to ensure temporal consistency. * * @param entries The set of entries to insert. Must not be <code>null</code>. If the set is empty, this method is * effectively a no-op. * @param force Setting this parameter to <code>true</code> will force the insertion of the given entries, bypassing * most sanity checks. */ public void insertEntries(Set<ChronoDBEntry> entries, boolean force); // ================================================================================================================= // DEBUG METHODS // ================================================================================================================= /** * Executes the given debug action before the primary index update occurs. * * <p> * This method is intended for debugging purposes only and should not be used during normal operation. * * @param action The action to be executed. Must not be <code>null</code>. */ public void setDebugCallbackBeforePrimaryIndexUpdate(final Consumer<ChronoDBTransaction> action); /** * Executes the given debug action before the secondary index update occurs. * * <p> * This method is intended for debugging purposes only and should not be used during normal operation. * * @param action The action to be executed. Must not be <code>null</code>. */ public void setDebugCallbackBeforeSecondaryIndexUpdate(final Consumer<ChronoDBTransaction> action); /** * Executes the given debug action before the commit metadata update occurs. * * <p> * This method is intended for debugging purposes only and should not be used during normal operation. * * @param action The action to be executed. Must not be <code>null</code>. */ public void setDebugCallbackBeforeMetadataUpdate(final Consumer<ChronoDBTransaction> action); /** * Executes the given debug action before the cache update occurs. * * <p> * This method is intended for debugging purposes only and should not be used during normal operation. * * @param action The action to be executed. Must not be <code>null</code>. */ public void setDebugCallbackBeforeCacheUpdate(final Consumer<ChronoDBTransaction> action); /** * Executes the given debug action before the update of the {@linkplain Branch#getNow() now} timestamp occurs. * * <p> * This method is intended for debugging purposes only and should not be used during normal operation. * * @param action The action to be executed. Must not be <code>null</code>. */ public void setDebugCallbackBeforeNowTimestampUpdate(final Consumer<ChronoDBTransaction> action); /** * Executes the given debug action before the transaction commit occurs. * * <p> * This method is intended for debugging purposes only and should not be used during normal operation. * * @param action The action to be executed. Must not be <code>null</code>. */ public void setDebugCallbackBeforeTransactionCommitted(final Consumer<ChronoDBTransaction> action); /** * Calculates the Head Chunk Statistics. * * @return The statistics for the given branch. Never <code>null</code>. */ public BranchHeadStatistics calculateBranchHeadStatistics(); /** * Updates the keyspace creation timestamp of the given keyspace to the given timestamp. * * @param keyspaceName The name of the keyspace to update the earliest commit for. Must not be <code>null</code>. * @param earliestCommit The new keyspace creation timestamp to assign to the keyspace. Must not be negative. */ public void updateCreationTimestampForKeyspace(final String keyspaceName, final long earliestCommit); }
73,658
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
BranchInternal.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/api/BranchInternal.java
package org.chronos.chronodb.internal.api; import org.chronos.chronodb.api.Branch; import org.chronos.chronodb.internal.impl.IBranchMetadata; /** * An extended version of the {@link Branch} interface. * * <p> * This interface and its methods are for internal use only, are subject to change and are not considered to be part of the public API. Down-casting objects to internal interfaces may cause application code to become incompatible with future releases, and is therefore strongly discouraged. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public interface BranchInternal extends Branch { /** * Returns the metadata associated with this branch. * * @return The metadata. Never <code>null</code>. */ public IBranchMetadata getMetadata(); /** * Returns the {@link TemporalKeyValueStore} for this branch. * * <p> * This method is <b>not</b> considered to be part of the public API. API users should never call this method directly, as it is intended for internal use only. * * @return The temporal key-value store that represents this branch. Never <code>null</code>. */ public TemporalKeyValueStore getTemporalKeyValueStore(); /** * Associates the given {@link TemporalKeyValueStore} with this branch. * * @param tkvs * The temporal key value store to use in this branch. Must not be <code>null</code>. Must not be owned by any other branch. */ public void setTemporalKeyValueStore(final TemporalKeyValueStore tkvs); }
1,515
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
GetResult.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/api/GetResult.java
package org.chronos.chronodb.internal.api; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.internal.impl.temporal.GetResultImpl; /** * A {@link GetResult} is returned by a {@link TemporalDataMatrix#get(long, String)}. * * <p> * It represents the result of a {@link TemporalDataMatrix#get(long, String)} call and includes the actual * {@linkplain #getValue() value} as well as the associated {@linkplain #getPeriod() validity period}. * * <p> * Please note that the time range will <b>always include</b> the timestamp which was requested. Requesting different * timestamps may produce different ranges on the same key. It is guaranteed that these ranges <b>do not overlap</b> for * the same key. * * @param <T> * The return type of the {@link #getValue()} method. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public interface GetResult<T> { // ===================================================================================================================== // STATIC FACTORY METHODS // ===================================================================================================================== /** * Creates a new {@link GetResult} with no value and the given range. * * <p> * The returned object will have {@link #isHit()} set to <code>false</code>. * * @param requestedKey * The key which was requested when this result is being produced. Must not be <code>null</code>. * @param range * The range in which the result is valid. Must not be <code>null</code>. * * * @return The new ranged result. Never <code>null</code>. */ public static <T> GetResult<T> createNoValueResult(final QualifiedKey requestedKey, final Period range) { return GetResultImpl.createNoValueResult(requestedKey, range); } /** * Creates a new {@link GetResult} with the given value and range. * * @param requestedKey * The key which was requested when this result is being produced. Must not be <code>null</code>. * @param value * The value which is to be contained in the result. May be <code>null</code> to indicate that there is * no value. * @param range * The range in which the result is valid. Must not be <code>null</code>. * * @return The new ranged result. Never <code>null</code>. */ public static <T> GetResult<T> create(final QualifiedKey requestedKey, final T value, final Period range) { return GetResultImpl.create(requestedKey, value, range); } /** * Creates a new {@link GetResult} that has the same properties as the given one, except it uses the given period * instead of the original one. * * @param getResult * The original {@link GetResult} to take the properties from. Must not be <code>null</code>. Will not be * modified. * @param newPeriod * The new period to use instead of the one contained in the given {@link GetResult}. * @return A new {@link GetResult} that is exactly the same as the given one, except that it uses the given period. */ public static <T> GetResult<T> alterPeriod(final GetResult<T> getResult, final Period newPeriod) { return GetResultImpl.alterPeriod(getResult, newPeriod); } // ===================================================================================================================== // PUBLIC API // ===================================================================================================================== /** * Returns the {@link QualifiedKey} which was requested when this result instance was created. * * @return The requested qualified key. Never <code>null</code>. */ public QualifiedKey getRequestedKey(); /** * Returns the range of this result. * * <p> * The range is a period that represents the set of timestamps in which the result is valid. * * @return The range period. Never <code>null</code>. */ public Period getPeriod(); /** * The value of the result. * * @return The value of this result. May be <code>null</code> to indicate that no value was found. */ public T getValue(); /** * Decides if this get result represents a "hit", i.e. the search ended up in a concrete entry. * * <p> * This method returns <code>false</code> in case that no entry matched the query. It returns <code>true</code> if * an entry matched the query, even if that entry represents a deletion. * * <p> * If this method returns <code>false</code>, then {@link #getValue()} will always return <code>null</code> (no * match found). Otherwise, {@link #getValue()} may return <code>null</code> to indicate an explicit deletion, or a * non- <code>null</code> value to indicate an insert/update. * * @return <code>true</code> if the search produced a concrete result, or <code>false</code> if no key matched the * query. */ public boolean isHit(); }
4,963
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
BranchEventListener.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/api/BranchEventListener.java
package org.chronos.chronodb.internal.api; import org.chronos.chronodb.api.Branch; import org.jetbrains.annotations.NotNull; public interface BranchEventListener { public void onBranchCreated(@NotNull Branch branch); public void onBranchDeleted(@NotNull Branch branch); }
285
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
Period.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/api/Period.java
package org.chronos.chronodb.internal.api; import static com.google.common.base.Preconditions.*; import org.chronos.chronodb.internal.impl.temporal.PeriodImpl; /** * A {@link Period} is a range (or interval) of timestamps. * * <p> * This interface represents a generic, general purpose Period. The period is defined by two {@link Long} values: * <ul> * <li>The lower bound (see: {@link #getLowerBound()}). This value is always <b>included</b> in the period. * <li>The upper bound (see: {@link #getUpperBound()}). This value is always <b>excluded</b> from the period. * </ul> * * In mathematical notation, the period <code>P</code> is therefore defined as: * * <pre> * P := [lower;upper[ * </pre> * * Containment of a given timestamp in a given period can be determined via {@link #contains(long)}. Note that this * class also implements {@link Comparable}, by comparing the <b>lower bounds</b> of any two periods. * * <p> * A period can also be <i>empty</i>, in which case {@link #isEmpty()} returns <code>true</code>. In an empty period, * {@link #contains(long)} will always return <code>false</code>. The bounds of an empty period can be arbitrary, but * the lower bound must be at least as large as the upper bound, and both bounds must refer to non-negative values. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public interface Period extends Comparable<Period> { // ===================================================================================================================== // STATIC FACTORY METHODS // ===================================================================================================================== /** * Returns an empty period. * * <p> * An empty period is a period where {@link #contains(long)} always returns <code>false</code>, and the * {@link #getLowerBound()} is greater than or equal to {@link #getUpperBound()}. In this implementation, * {@link #getLowerBound()} and {@link #getUpperBound()} both return zero. * * @return The empty period. Never <code>null</code>. */ public static Period empty() { return PeriodImpl.empty(); } /** * Returns the "eternal" period, i.e. the period that contains all non-negative timestamps. * * @return The eternal period. Never <code>null</code>. */ public static Period eternal() { return PeriodImpl.eternal(); } /** * Creates a period that contains a range of timestamps. * * <p> * This method can <b>not</b> be used to create empty periods. Please use {@link #empty()} instead. * * @param lowerBoundInclusive * The lower bound timestamp to be included in the new period. Must not be negative. Must be strictly * smaller than <code>upperBoundExclusive</code>. * @param upperBoundExclusive * The upper bound timestamp to be exclused from the period. Must not be negative. Must be strictly * larger than <code>lowerBoundInclusive</code>. * * @return A new period with the given range of timestamps. */ public static Period createRange(final long lowerBoundInclusive, final long upperBoundExclusive) { return PeriodImpl.createRange(lowerBoundInclusive, upperBoundExclusive); } /** * Creates a new {@link Period} that starts at the given lower bound (inclusive) and is open-ended. * * <p> * In other words, {@link #contains(long)} will always return <code>true</code> for all timestamps greater than or * equal to the given one. * * <p> * Calling {@link #getUpperBound()} on the resulting period will return {@link Long#MAX_VALUE}. * * @param lowerBound * The lower bound to use for the new range period. Must not be negative. * * @return A period that starts at the given lower bound (inclusive) and is open-ended. */ public static Period createOpenEndedRange(final long lowerBound) { return PeriodImpl.createOpenEndedRange(lowerBound); } /** * Creates a new {@link Period} that contains only one point in time, which is the given timestamp. * * <p> * In other words, {@link #contains(long)} will always return <code>false</code> for all timestamps, except for the * given one. * * <p> * The lower bound of the period will be set to the given timestamp (as it is inclusive), the upper bound will be * set to the given timestamp + 1 (exclusive). * * @param timestamp * The timestamp which should be contained in the resulting period. Must not be negative. * @return A period that contains only the given timestamp. Never <code>null</code>. */ public static Period createPoint(final long timestamp) { return PeriodImpl.createPoint(timestamp); } // ===================================================================================================================== // API // ===================================================================================================================== /** * Returns the timestamp that represents the lower bound of this period. * * <p> * The lower bound is always included in a period. Therefore calling: * * <pre> * period.contains(period.getLowerBound()) * </pre> * * ... always returns <code>true</code>, <i>unless</i> the period is empty. * * <p> * The lower bound timestamp is always a value greater than or equal to zero. In all non-empty periods, the lower * bound is strictly smaller than the upper bound. * * @return The timestamp that represents the lower bound. */ public long getLowerBound(); /** * Returns the timestamp that represents the upper bound of this period. * * <p> * The upper bound is always excluded from a period. Therefore calling: * * <pre> * period.contains(period.getUpperBound()) * </pre> * * ... always returns <code>false</code>. * * <p> * The upper bound is a always a value greater than or equal to zero. In all non-empty periods, the upper bound is * strictly larger than the lower bound. * * @return The timestamp that represents the upper bound. */ public long getUpperBound(); // ===================================================================================================================== // DEFAULT IMPLEMENTATIONS // ===================================================================================================================== /** * Checks if the given timestamp is contained in (i.e. part of) this period. * * <p> * A timestamp is contained in a period if the following condition holds: * * <pre> * p.lowerBound <= timestamp < p.upperBound * </pre> * * <p> * This method always returns <code>false</code> (regardless of the argument) if this period is empty. * * @param timestamp * The timestamp to check. Must not be negative. * * @return <code>true</code> if the given timestamp is contained in this period, otherwise <code>false</code>. */ public default boolean contains(final long timestamp) { checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); if (this.isEmpty()) { return false; } return this.getLowerBound() <= timestamp && timestamp < this.getUpperBound(); } /** * Checks if this period is empty or not. * * <p> * A period <code>p</code> is empty if and only if there is no valid timestamp <code>t</code> for which * * <pre> * p.contains(t) * </pre> * * returns <code>true</code>. In empty periods, {@link #getLowerBound()} always returns a value that is greater than * or equal to the value returned by {@link #getUpperBound()}. * * @return <code>true</code> if this period is empty, otherwise <code>false</code>. */ public default boolean isEmpty() { return this.getLowerBound() >= this.getUpperBound(); } /** * Checks if there is an overlap between this period and the given period. * * <p> * Two periods <code>P1</code> and <code>P2</code> overlap each other, if there is at least one timestamp * <code>t</code> where * * <pre> * P1.contains(t) && P2.contains(t) * </pre> * * ... returns <code>true</code>. In other words, two periods overlap if there is at least one timestamp which is * contained in both periods. * * <p> * If either <code>this</code> period or the <code>other</code> period is empty, this method will always return * <code>false</code>. * * @param other * The period to check for an overlap with. Must not be <code>null</code>. * * @return <code>true</code> if there is an overlap between this and the other period, otherwise <code>false</code>. */ public default boolean overlaps(final Period other) { checkNotNull(other, "Precondition violation - argument 'other' must not be NULL!"); if (this.isEmpty() || other.isEmpty()) { // there is never an overlap between empty and other periods return false; } if (this.isStrictlyAfter(other)) { return false; } if (this.isStrictlyBefore(other)) { return false; } // if this period is neither strictly before, nor strictly after the other period, then there must be an overlap return true; } /** * Checks if this period fully contains the other period. * * <p> * A period <code>P1</code> contains a period <code>P2</code> if, for all timestamps <code>t</code> in * <code>P2</code> * * <pre> * P1.contains(t) * </pre> * * ... returns <code>true</code>. In other words, a period is contained in another period if all timestamps from the * first period are also contained in the second period. * * <p> * If either <code>this</code> period or the <code>other</code> period is empty, this method returns * <code>false</code>. * * @param other * The other period to check if it is contained in this period. Must not be <code>null</code>. * * @return <code>true</code> if this period contains the other period, otherwise <code>false</code>. */ public default boolean contains(final Period other) { checkNotNull(other, "Precondition violation - argument 'other' must not be NULL!"); if (this.isEmpty() || other.isEmpty()) { // there is never a containment relationship between empty and other periods return false; } if (this.getLowerBound() <= other.getLowerBound() && this.getUpperBound() >= other.getUpperBound()) { return true; } else { return false; } } /** * Checks if this period is adjacent to the other period. * * <p> * A period <code>P1</code> is adjacent to another period <code>P2</code> if: * * <pre> * P1.upperBound == P2.lowerBound || P1.lowerBound == P2.upperBound * </pre> * * In other words, two periods are adjacent to each other if there is no timestamp that is between them, but not * part of either one of them. * * <p> * Note that overlapping periods are never adjacent to each other. * * <p> * If either <code>this</code> period or the <code>other</code> period is empty, this method returns * <code>false</code>. * * @param other * The other period to check adjacency against. Must not be <code>null</code>. * * @return <code>true</code> if this period is adjacent to the other period, otherwise <code>false</code>. */ public default boolean isAdjacentTo(final Period other) { checkNotNull(other, "Precondition violation - argument 'other' must not be NULL!"); if (this.isEmpty() || other.isEmpty()) { // there is never an adjacency relationship between empty and other periods return false; } if (this.getLowerBound() == other.getUpperBound() || this.getUpperBound() == other.getLowerBound()) { return true; } else { return false; } } /** * Checks if this period starts before the other period. * * <p> * A period <code>P1</code> is before another period <code>P2</code> if and only if: * * <pre> * P1.lowerBound < P2.lowerBound * </pre> * * Note that there is no restriction on the upper bounds. Therefore, partially overlapping periods can also be in an * "is before" relation with each other. * * <p> * If either <code>this</code> period or the <code>other</code> period is empty, this method returns * <code>false</code>. * * @param other * The other period to check the "is before" relation against. Must not be <code>null</code>. * * @return <code>true</code> if this period is before the other period, otherwise <code>false</code>. * * @see #isAfter(Period) * @see #isStrictlyBefore(Period) * @see #isStrictlyAfter(Period) */ public default boolean isBefore(final Period other) { checkNotNull(other, "Precondition violation - argument 'other' must not be NULL!"); if (this.isEmpty() || other.isEmpty()) { // there is never an "is before" relationship between empty and other periods return false; } if (this.getLowerBound() < other.getLowerBound()) { return true; } else { return false; } } /** * Checks if this period starts before the given timestamp (and does not include it). * * A period <code>P</code> is before a timestamp <code>T</code> if and only if: * * <pre> * P.upperBound <= T * </pre> * * <p> * If this period is empty, this method returns <code>false</code>. * * @param timestamp * The timestamp to check the "is before" relation against. Must not be negative. * @return <code>true</code> if this period is before the given timestamp, otherwise <code>false</code>. */ public default boolean isBefore(final long timestamp) { checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); if (this.isEmpty()) { // by definition... return false; } if (this.getUpperBound() <= timestamp) { return true; } else { return false; } } /** * Checks if this period starts after the other period. * * <p> * A period <code>P1</code> is after another period <code>P2</code> if and only if: * * <pre> * P1.lowerBound > P2.lowerBound * </pre> * * Note that there is no restriction on the upper bounds. Therefore, partially overlapping periods can also be in an * "is after" relation with each other. * * <p> * If either <code>this</code> period or the <code>other</code> period is empty, this method returns * <code>false</code>. * * @param other * The other period to check the "is after" relation against. Must not be <code>null</code>. * * @return <code>true</code> if this period is after the other period, otherwise <code>false</code>. * * @see #isBefore(Period) * @see #isStrictlyBefore(Period) * @see #isStrictlyAfter(Period) */ public default boolean isAfter(final Period other) { checkNotNull(other, "Precondition violation - argument 'other' must not be NULL!"); if (this.isEmpty() || other.isEmpty()) { // there is never an "is after" relationship between empty and other periods return false; } if (this.getLowerBound() > other.getLowerBound()) { return true; } else { return false; } } /** * Checks if this period starts after the given timestamp. * * A period <code>P</code> is after a timestamp <code>T</code> if and only if: * * <pre> * P.lowerBound > T * </pre> * * <p> * If this period is empty, this method returns <code>false</code>. * * @param timestamp * The timestamp to check the "is after" relation against. Must not be negative. * @return <code>true</code> if this period is after the given timestamp, otherwise <code>false</code>. */ public default boolean isAfter(final long timestamp) { checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); if (this.isEmpty()) { // by definition... return false; } if (this.getLowerBound() > timestamp) { return true; } else { return false; } } /** * Checks if this period starts and ends before the other period starts. * * <p> * A period <code>P1</code> is strictly before another period <code>P2</code> if and only if: * * <pre> * P1.lowerBound < P2.lowerBound && P1.upperBound <= P2.lowerBound * </pre> * * <p> * If either <code>this</code> period or the <code>other</code> period is empty, this method returns * <code>false</code>. * * @param other * The other period to check the "is strictly before" relation against. Must not be <code>null</code>. * * @return <code>true</code> if this period is strictly before the other period, otherwise <code>false</code>. * * @see #isBefore(Period) * @see #isAfter(Period) * @see #isStrictlyAfter(Period) */ public default boolean isStrictlyBefore(final Period other) { checkNotNull(other, "Precondition violation - argument 'other' must not be NULL!"); if (this.isEmpty() || other.isEmpty()) { // there is never an "is strictly before" relationship between empty and other periods return false; } if (this.getLowerBound() < other.getLowerBound() && this.getUpperBound() <= other.getLowerBound()) { return true; } else { return false; } } /** * Checks if this period starts after the other period ends. * * <p> * A period <code>P1</code> is strictly after another period <code>P2</code> if and only if: * * <pre> * P1.lowerBound >= P2.upperBound * </pre> * * <p> * If either <code>this</code> period or the <code>other</code> period is empty, this method returns * <code>false</code>. * * @param other * The other period to check the "is strictly after" relation against. Must not be <code>null</code>. * * @return <code>true</code> if this period is strictly after the other period, otherwise <code>false</code>. * * @see #isBefore(Period) * @see #isAfter(Period) * @see #isStrictlyBefore(Period) */ public default boolean isStrictlyAfter(final Period other) { checkNotNull(other, "Precondition violation - argument 'other' must not be NULL!"); if (this.isEmpty() || other.isEmpty()) { // there is never an "is strictly after" relationship between empty and other periods return false; } if (this.getLowerBound() >= other.getUpperBound()) { return true; } else { return false; } } /** * Checks if this period has an open end. * * <p> * A period is open-ended if {@link #getUpperBound()} is equal to {@link Long#MAX_VALUE}. * * <p> * Note that an empty period is never open-ended. For empty periods, this method always returns <code>false</code>. * * @return <code>true</code> if this period is open-ended, otherwise <code>false</code>. */ public default boolean isOpenEnded() { if (this.isEmpty()) { // there can never be an open-ended empty period return false; } return this.getUpperBound() == Long.MAX_VALUE; } /** * Returns the length of this period. * * <p> * The length of a period is defined as the number of different timestamps which are contained in this period. * * <p> * For the empty period, this method always returns zero. For all other periods, a non-negative number is returned. * * @return The number of different timestamps contained in this period. */ public default long length() { if (this.isEmpty()) { return 0; } return this.getUpperBound() - this.getLowerBound(); } /** * Creates a duplicate of this period, replacing the original upper bound with the given upper bound. * * <p> * <code>this</code> will not be modified. * * <p> * Please note that this method does not allow to create empty ranges, i.e. the new upper bound must always be * strictly larger than the lower bound. * * <p> * This operation is only allowed on non-empty periods. This method throws an {@link IllegalStateException} if the * original period is empty. * * @param newUpperBound * The new upper bound to use. Must not be negative. * * @return The new period with the given upper bound. */ public default Period setUpperBound(final long newUpperBound) { checkArgument(newUpperBound > this.getLowerBound(), "Precondition violation - argument 'newUpperBound' must be strictly larger than the current lower bound!"); if (this.isEmpty()) { throw new IllegalStateException("Cannot use #setUpperBound(...) on empty periods!"); } return Period.createRange(getLowerBound(), newUpperBound); } /** * Intersects this period with the given <code>other</code> period. * * <p> * Creates a new period for the result, neither this period nor the given other period will be changed. * </p> * * <p> * An intersection with an empty period will always return the empty period. * </p> * * @param other The other period. Must not be <code>null</code>. * @return A new period, representing the intersection of this period and the given <code>other</code> period. */ public default Period intersection(final Period other){ checkNotNull(other, "Precondition violation - argument 'other' must not be NULL!"); if(other.isEmpty()){ return Period.empty(); } if(other.contains(this)){ return this; } if(this.contains(other)){ return other; } if(!this.overlaps(other)){ // no overlap -> intersection is empty return Period.empty(); } // create the intersection long lowerBound = Math.max(this.getLowerBound(), other.getLowerBound()); long upperBound = Math.min(this.getUpperBound(), other.getUpperBound()); if(lowerBound >= upperBound){ return Period.empty(); } return Period.createRange(lowerBound, upperBound); } /** * Compares this period to the given period. * * <p> * Two periods are compared by comparing the <b>lower bounds</b>. The upper bounds are <b>ignored</b> in the * comparison. * * @param other * The other period to compare this period to * * @return A value less than, equal to, or larger than zero if <code>this</code> period is less than, equal to, or * larger than the <code>other</code> period. */ @Override public default int compareTo(final Period other) { if (other == null) { return 1; } if (other.isEmpty() && this.isEmpty() == false) { return 1; } return Long.compare(this.getLowerBound(), other.getLowerBound()); } }
22,213
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
TransactionConfigurationInternal.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/api/TransactionConfigurationInternal.java
package org.chronos.chronodb.internal.api; import org.chronos.chronodb.api.ChronoDBTransaction; /** * An extended version of {@link org.chronos.chronodb.api.ChronoDBTransaction.Configuration}. * * <p> * This interface and its methods are for internal use only, are subject to change and are not considered to be part of * the public API. Down-casting objects to internal interfaces may cause application code to become incompatible with * future releases, and is therefore strongly discouraged. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API */ public interface TransactionConfigurationInternal extends ChronoDBTransaction.Configuration { /** * Returns the branch on which the resulting transaction should operate. * * @return The branch. Never <code>null</code>. */ public String getBranch(); /** * Checks if the resulting transaction should operate on the "now" timestamp of the target branch. * * @return <code>true</code> if the resulting transaction should operate on the target branch, otherwise * <code>false</code>. */ public default boolean isTimestampNow() { return this.getTimestamp() == null; } /** * Returns the timestamp on which the resulting transaction should operate. * * @return The configured timestamp, or <code>null</code> if the transaction should operate on the "now" timestamp * of the target branch. */ public Long getTimestamp(); /** * Checks whether this transaction is allowed during dateback. * * @return <code>true</code> if this transaction is permitted during dateback, otherwise <code>false</code>. */ public boolean isAllowedDuringDateback(); }
1,755
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoDBFactoryInternal.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/api/ChronoDBFactoryInternal.java
package org.chronos.chronodb.internal.api; import org.apache.commons.configuration2.Configuration; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBFactory; import org.chronos.chronodb.api.exceptions.ChronoDBConfigurationException; import org.chronos.chronodb.internal.impl.builder.database.ChronoDBFactoryImpl; /** * Extended version of the {@link ChronoDBFactory} interface. * * <p> * This interface and its methods are for internal use only, are subject to change and are not considered to be part of * the public API. Down-casting objects to internal interfaces may cause application code to become incompatible with * future releases, and is therefore strongly discouraged. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public interface ChronoDBFactoryInternal extends ChronoDBFactory { // ================================================================================================================= // STATIC PART // ================================================================================================================= /** The static factory instance. */ public static final ChronoDBFactoryInternal INSTANCE = new ChronoDBFactoryImpl(); // ================================================================================================================= // PUBLIC API // ================================================================================================================= /** * Creates a new {@link ChronoDB} instance based on the given configuration. * * @param configuration * The configuration to use. Must not be <code>null</code>. * @return The newly created ChronoDB instance. * * @throws ChronoDBConfigurationException * Thrown if the configuration is invalid. */ public ChronoDB create(final Configuration configuration) throws ChronoDBConfigurationException; }
1,936
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
StatisticsManagerInternal.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/api/StatisticsManagerInternal.java
package org.chronos.chronodb.internal.api; import org.chronos.chronodb.api.StatisticsManager; public interface StatisticsManagerInternal extends StatisticsManager { public void updateBranchHeadStatistics(String branchName, long inserts, long updates, long deletes); public void clearBranchHeadStatistics(); public void clearBranchHeadStatistics(String branchName); }
384
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
DatebackManagerInternal.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/api/DatebackManagerInternal.java
package org.chronos.chronodb.internal.api; import org.chronos.chronodb.api.DatebackManager; import org.chronos.chronodb.internal.api.dateback.log.DatebackOperation; public interface DatebackManagerInternal extends DatebackManager { /** * Adds the given operation to the databack log. * * <p> * <b>/!\ For internal purposes only.</b> * </p> * * @param operation The operation to add to the log. Must not be <code>null</code>. */ public void addDatebackOperationToLog(DatebackOperation operation); public void deleteLogsForBranch(String branchName); }
607
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
MigrationChain.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/api/migration/MigrationChain.java
package org.chronos.chronodb.internal.api.migration; import java.util.List; import org.chronos.chronodb.internal.api.ChronoDBInternal; import org.chronos.chronodb.internal.api.migration.annotations.Migration; import org.chronos.chronodb.internal.impl.migration.MigrationChainImpl; import org.chronos.common.version.ChronosVersion; public interface MigrationChain<DBTYPE extends ChronoDBInternal> extends Iterable<Class<? extends ChronosMigration<DBTYPE>>> { // ================================================================================================================= // STATIC FACTORY METHODS // ================================================================================================================= /** * Creates a new {@link MigrationChain} from the given Java package name. * * <p> * This method will scan all classes in the package, looking for classes that extend {@link ChronosMigration} and have an <code>@</code>{@link Migration} annotation. * * <p> * The following conditions apply on the {@link ChronosMigration} classes: * <ul> * <li>The classes must be top-level classes, i.e. they must not be nested. * <li>The classes must implement {@link ChronosMigration}. * <li>The classes must be annotated with <code>@</code>{@link Migration} (directly; inheriting this annotation is not supported). * <li>The classes must have a default constructor. * <li>The version ranges given by the <code>@</code>{@link Migration} interfaces must not intersect. * </ul> * * @param qualifiedPackageName * The fully qualified name of the java package to scan. Must not be <code>null</code>. * * @return The migration chain of classes found in the given package. Never <code>null</code>, may be empty. */ public static <DBTYPE extends ChronoDBInternal> MigrationChain<DBTYPE> fromPackage(final String qualifiedPackageName) { return MigrationChainImpl.fromPackage(qualifiedPackageName); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= /** * Returns the migration classes found in this chain. * * @return The list of migration classes (unmodifiable view). May be empty, but never <code>null</code>. */ public List<Class<? extends ChronosMigration<DBTYPE>>> getMigrationClasses(); /** * Produces a sub-migration-chain from this instance by limiting the migration classes to the ones starting at or after the given version (inclusive). * * @param from * The minimal chronos version to be migrated from in the result chain (inclusive). Must not be <code>null</code>. * @return The new migration chain with the limited scope. Never <code>null</code>, may be empty. */ public MigrationChain<DBTYPE> startingAt(ChronosVersion from); /** * Executes this migration chain on the given {@link ChronoDBInternal ChronoDB} instance. * * @param chronoDB * The DB to migrate. Must not be <code>null</code>. */ public void execute(DBTYPE chronoDB); }
3,173
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronosMigration.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/api/migration/ChronosMigration.java
package org.chronos.chronodb.internal.api.migration; import org.chronos.chronodb.internal.api.ChronoDBInternal; public interface ChronosMigration<DBTYPE extends ChronoDBInternal> { public void execute(DBTYPE chronoDB); }
226
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
Migration.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/api/migration/annotations/Migration.java
package org.chronos.chronodb.internal.api.migration.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Documented @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface Migration { String from(); String to(); }
407
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
QueryManager.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/api/query/QueryManager.java
package org.chronos.chronodb.internal.api.query; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.builder.query.QueryBuilderFinalizer; import org.chronos.chronodb.api.builder.query.QueryBuilderStarter; /** * The {@link QueryManager} is responsible for providing access to a number of objects related to queries in a given * {@link ChronoDB} instance. * * <p> * In particular, these objects include the following: * <ul> * <li>{@link QueryParser}: The query parser used for parsing {@link QueryTokenStream}s * <li>{@link QueryOptimizer}: The optimizer which is run on every {@link ChronoDBQuery} before executing it * <li>{@link QueryBuilderStarter}: The query builder implementation * </ul> * * All of the above interfaces require implementations that agree with each other and belong together. The query manager * acts as the container and/or factory for these implementation class instances. * * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public interface QueryManager { /** * Returns the {@link QueryParser} implementation. * * <p> * It is assumed that this method will constantly return the same object (with respect to the <code>==</code> * operator). * * @return The query parser to be used. Never <code>null</code>. */ public QueryParser getQueryParser(); /** * Returns the {@link QueryOptimizer} implementation. * * <p> * It is assumed that this method will constantly return the same object (with respect to the <code>==</code> * operator). * * @return The query optimizer to be used. Never <code>null</code>. */ public QueryOptimizer getQueryOptimizer(); /** * Returns a new instance of the {@link QueryBuilderStarter} class associated with this query manager. * * <p> * This is essentially a factory method for the concrete implementation of {@link QueryBuilderStarter}. It must * return a <b>new</b> instance on every call. * * * @param tx * The transaction on which the query is being built. Must not be <code>null</code>. * * @return A new instance of the query builder implementation. */ public QueryBuilderStarter createQueryBuilder(ChronoDBTransaction tx); /** * Returns a new instance of the {@link QueryBuilderFinalizer} class associated with this query manager. * * <p> * This is essentially a factory method for the concrete implementation of {@link QueryBuilderFinalizer}. It must * return a <b>new</b> instance on every call. * * @param tx * The transaction on which the query is being executed. Must not be <code>null</code>. * @param query * The query to execute on the transaction. Must not be <code>null</code>. * * @return A new instance of the query builder finalizer implementation. */ public QueryBuilderFinalizer createQueryBuilderFinalizer(ChronoDBTransaction tx, ChronoDBQuery query); }
2,979
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z