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
StringContainmentCondition.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/api/query/StringContainmentCondition.java
package org.chronos.chronodb.api.query; import org.chronos.chronodb.internal.impl.query.TextMatchMode; import org.chronos.chronodb.internal.impl.query.condition.containment.SetWithoutStringCondition; import org.chronos.chronodb.internal.impl.query.condition.containment.StringWithinSetCondition; import java.util.Set; public interface StringContainmentCondition extends ContainmentCondition { public static StringContainmentCondition WITHIN = StringWithinSetCondition.INSTANCE; public static StringContainmentCondition WITHOUT = SetWithoutStringCondition.INSTANCE; /** * Negates this condition. * * @return The negated condition. */ public StringContainmentCondition negate(); /** * Applies this condition. * * @param elementToTest The element to check. May be <code>null</code>. * @param collectionToTestAgainst The collection to check against. <code>null</code> will be treated as empty collection. * @param matchMode The text match mode to use when testing containment. Must not be <code>null</code>. * @return <code>true</code> if this condition applies, otherwise <code>false</code>. */ public boolean applies(String elementToTest, Set<String> collectionToTestAgainst, TextMatchMode matchMode); }
1,288
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ContainmentCondition.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/api/query/ContainmentCondition.java
package org.chronos.chronodb.api.query; /** * A {@link ContainmentCondition} is a {@link Condition} on any values, checking for (non-)containment in a known collection. * * @author martin.haeusler@txture.io -- Initial Contribution and API * */ public interface ContainmentCondition extends Condition { /** * Negates this condition. * * @return The negated condition. */ public ContainmentCondition negate(); }
446
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
DoubleContainmentCondition.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/api/query/DoubleContainmentCondition.java
package org.chronos.chronodb.api.query; import org.chronos.chronodb.internal.impl.query.condition.containment.DoubleWithinSetCondition; import org.chronos.chronodb.internal.impl.query.condition.containment.SetWithoutDoubleCondition; import java.util.Set; public interface DoubleContainmentCondition extends ContainmentCondition { public static DoubleContainmentCondition WITHIN = DoubleWithinSetCondition.INSTANCE; public static DoubleContainmentCondition WITHOUT = SetWithoutDoubleCondition.INSTANCE; /** * Negates this condition. * * @return The negated condition. */ public DoubleContainmentCondition negate(); /** * Applies this condition. * * @param elementToTest The element to check. May be <code>null</code>. * @param collectionToTestAgainst The collection to check against. <code>null</code> will be treated as empty collection. * @param tolerance The equality tolerance to apply when checking for containment. * @return <code>true</code> if this condition applies, otherwise <code>false</code>. */ public boolean applies(double elementToTest, Set<Double> collectionToTestAgainst, double tolerance); }
1,197
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
NumberCondition.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/api/query/NumberCondition.java
package org.chronos.chronodb.api.query; import java.util.List; import org.chronos.chronodb.internal.impl.query.condition.number.GreaterThanCondition; import org.chronos.chronodb.internal.impl.query.condition.number.GreaterThanOrEqualToCondition; import org.chronos.chronodb.internal.impl.query.condition.number.LessThanCondition; import org.chronos.chronodb.internal.impl.query.condition.number.LessThanOrEqualToCondition; /** * A {@link NumberCondition} is a {@link Condition} on numeric (i.e. <code>int</code>, <code>long</code>, <code>float</code>, <code>double</code>...) values. * * <p> * This class comes with two different {@linkplain #applies(long, long) apply} methods, one for <code>long</code>s and one for <code>double</code>s. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public interface NumberCondition extends Condition { // ================================================================================================================= // CONSTANTS // ================================================================================================================= /** The (strictly) greater-than condition <code>&gt;</code>. */ public static final NumberCondition GREATER_THAN = GreaterThanCondition.INSTANCE; /** The greater-than-or-equal-to condition <code>&gt;=</code>. */ public static final NumberCondition GREATER_EQUAL = GreaterThanOrEqualToCondition.INSTANCE; /** The (strictly) less-than condition <code>&lt;</code>. */ public static final NumberCondition LESS_THAN = LessThanCondition.INSTANCE; /** The less-than-or-equal-to condition <code>&lt;=</code>. */ public static final NumberCondition LESS_EQUAL = LessThanOrEqualToCondition.INSTANCE; // ================================================================================================================= // FACTORY METHODS // ================================================================================================================= /** * Returns a list of all known {@link NumberCondition}s. * * @return The list of number conditions. Never <code>null</code>. */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static List<NumberCondition> values() { List conditions = Condition.values(); List<NumberCondition> resultList = conditions; resultList.add(GREATER_THAN); resultList.add(GREATER_EQUAL); resultList.add(LESS_THAN); resultList.add(LESS_EQUAL); return resultList; } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public NumberCondition negate(); /** * Applies <code>this</code> condition to the given index and search value. * * @param value * The value from the secondary index. Must not be <code>null</code>. * @param searchValue * The number to search for. Must not be <code>null</code>. * @return <code>true</code> if this condition applies (matches) given the parameters, otherwise <code>false</code> . */ public boolean applies(final long value, final long searchValue); /** * Applies <code>this</code> condition to the given index and search value. * * @param value * The value from the secondary index. Must not be <code>null</code>. * @param searchValue * The number to search for. Must not be <code>null</code>. * @return <code>true</code> if this condition applies (matches) given the parameters, otherwise <code>false</code> . */ public default boolean applies(final double value, final double searchValue) { return this.applies(value, searchValue, 0); } /** * Applies <code>this</code> condition to the given index and search value. * * @param value * The value from the secondary index. Must not be <code>null</code>. * @param searchValue * The number to search for. Must not be <code>null</code>. * @param equalityTolerance * The tolerance range for equality conditions. Will be applied in positive AND negative direction. Must not be negative. * @return <code>true</code> if this condition applies (matches) given the parameters, otherwise <code>false</code> . */ public boolean applies(final double value, final double searchValue, final double equalityTolerance); }
4,442
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
Condition.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/api/query/Condition.java
package org.chronos.chronodb.api.query; import java.util.List; import org.chronos.chronodb.internal.impl.query.condition.EqualsCondition; import org.chronos.chronodb.internal.impl.query.condition.NotEqualsCondition; import org.chronos.chronodb.internal.impl.query.parser.ast.WhereElement; import com.google.common.collect.Lists; /** * A condition is a comparison operation to be applied inside a {@link WhereElement} in the query language. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public interface Condition { // ================================================================================================================= // CONSTANTS // ================================================================================================================= /** Standard equality condition. */ public static final EqualsCondition EQUALS = EqualsCondition.INSTANCE; /** Inverted equality condition. */ public static final NotEqualsCondition NOT_EQUALS = NotEqualsCondition.INSTANCE; // ================================================================================================================= // FACTORY METHODS // ================================================================================================================= /** * Returns the list of all known {@link Condition}s (excluding instances of subclasses). * * @return The list of known conditions. Never <code>null</code>. */ public static List<Condition> values() { return Lists.newArrayList(EQUALS, NOT_EQUALS); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= /** * Returns the negated form of this condition. * * <p> * This also works for already negated conditions. The following statement is always true: * * <pre> * condition.getNegated().getNegated() == condition // always true * </pre> * * @return The negated condition. For already negated conditions, the regular non-negated condition will be returned. */ public Condition negate(); /** * Checks if this condition is negated or not. * * @return <code>true</code> if this is a negated condition, otherwise <code>false</code>. */ public default boolean isNegated() { return false; } /** * Checks if this condition accepts the empty value. * * @return <code>true</code> if this condition accepts the empty value, otherwise <code>false</code>. */ public default boolean acceptsEmptyValue() { return false; } /** * Returns the in-fix representation of this condition. * * @return The in-fix representation. Never <code>null</code>. */ public String getInfix(); }
2,832
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
StringCondition.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/api/query/StringCondition.java
package org.chronos.chronodb.api.query; import java.util.List; import org.chronos.chronodb.internal.impl.query.TextMatchMode; import org.chronos.chronodb.internal.impl.query.condition.string.ContainsCondition; import org.chronos.chronodb.internal.impl.query.condition.string.EndsWithCondition; import org.chronos.chronodb.internal.impl.query.condition.string.MatchesRegexCondition; import org.chronos.chronodb.internal.impl.query.condition.string.NotContainsCondition; import org.chronos.chronodb.internal.impl.query.condition.string.NotEndsWithCondition; import org.chronos.chronodb.internal.impl.query.condition.string.NotMatchesRegexCondition; import org.chronos.chronodb.internal.impl.query.condition.string.NotStartsWithCondition; import org.chronos.chronodb.internal.impl.query.condition.string.StartsWithCondition; /** * A {@link StringCondition} is a {@link Condition} on string values. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public interface StringCondition extends Condition { // ================================================================================================================= // CONSTANTS // ================================================================================================================= /** Checks if a string starts with a given character sequence. */ public static final StringCondition STARTS_WITH = StartsWithCondition.INSTANCE; /** Inverted starts-with condition. */ public static final StringCondition NOT_STARTS_WITH = NotStartsWithCondition.INSTANCE; /** Checks if a string ends with a given character sequence. */ public static final StringCondition ENDS_WITH = EndsWithCondition.INSTANCE; /** Inverted ends-with condition. */ public static final StringCondition NOT_ENDS_WITH = NotEndsWithCondition.INSTANCE; /** Checks if a string contains a given character sequence. */ public static final StringCondition CONTAINS = ContainsCondition.INSTANCE; /** Inverted contains condition. */ public static final StringCondition NOT_CONTAINS = NotContainsCondition.INSTANCE; /** Checks if a string matches a given {@linkplain java.util.regex.Pattern regular expression}. */ public static final StringCondition MATCHES_REGEX = MatchesRegexCondition.INSTANCE; /** Inverted regex matching condition. */ public static final StringCondition NOT_MATCHES_REGEX = NotMatchesRegexCondition.INSTANCE; // ================================================================================================================= // FACTORY METHODS // ================================================================================================================= /** * Returns a list of all known {@link StringCondition}s. * * @return The list of string conditions. Never <code>null</code>. */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static List<StringCondition> values() { List conditions = Condition.values(); List<StringCondition> resultList = conditions; resultList.add(STARTS_WITH); resultList.add(NOT_STARTS_WITH); resultList.add(ENDS_WITH); resultList.add(NOT_ENDS_WITH); resultList.add(CONTAINS); resultList.add(NOT_CONTAINS); resultList.add(MATCHES_REGEX); resultList.add(NOT_MATCHES_REGEX); return resultList; } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public StringCondition negate(); /** * Applies <code>this</code> condition to the given text and search value, considering the given match mode. * * @param text * The text to search in. Must not be <code>null</code>. * @param searchValue * The character sequence to search for. Must not be <code>null</code>. * @param matchMode * The text match mode to use. Must not be <code>null</code>. * @return <code>true</code> if this condition applies (matches) given the parameters, otherwise <code>false</code> . */ public boolean applies(final String text, final String searchValue, final TextMatchMode matchMode); }
4,208
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
StringIndexer.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/api/indexing/StringIndexer.java
package org.chronos.chronodb.api.indexing; import java.util.Set; import org.chronos.chronodb.api.ChronoDB; /** * A {@link StringIndexer} is an {@link Indexer} capable of extracting {@link String} values from an object. * * <p> * Please refer to the documentation in {@link Indexer} for more details. * * @author martin.haeulser@uibk.ac.at -- Initial Contribution and API */ public interface StringIndexer extends Indexer<String> { /** * Produces the indexed String values of the given object. * * <p> * This method is only called by {@link ChronoDB} if a previous call to {@link #canIndex(Object)} with the same parameter returned <code>true</code>. * * @param object * The object to index. Must not be <code>null</code>. * @return A {@link Set} of Strings representing the indexed values for the given object. <code>null</code>-values in the set will be ignored. If this method returns <code>null</code>, it will be treated as if it had returned an empty set. */ @Override public Set<String> getIndexValues(Object object); }
1,070
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
Indexer.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/api/indexing/Indexer.java
package org.chronos.chronodb.api.indexing; import java.util.Set; import org.chronos.chronodb.api.ChronoDB; /** * A {@link Indexer} is an object capable of producing an index value for a given object. * * <p> * Chrono Indexers are executed every time an object is saved in {@link ChronoDB} to produce the corresponding index entries. * * <p> * API users are free to implement their own indexer classes. However, a number of conditions apply. * <ul> * <li>All methods of this class must be <b>idempotent</b>, i.e. consistently return the same result on the same input. * <li>Instances of implementing classes must be <b>stateless</b> and in particular must <b>not</b> store references to other objects, unless they are "owned" by the indexer and not accessed anywhere else. * <li>Implementing classes must be serializable. ChronoDB will persist them and re-load them as required. * <li><b>Do not implement this interface directly!</b> Implement the sub-interfaces, e.g. {@link StringIndexer} or {@link LongIndexer} instead. * </ul> * * <p> * As a general best practice, consider implementing this interface with classes that <b>have no fields</b> and do not access any static fields and/or methods. * * <p> * For indexers that do have states (i.e. fields), the corresponding classes need to have a proper implementation of {@link #hashCode()} and {@link #equals(Object)}! * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * @param <T> * The return type of the {@link #getIndexValues(Object)} method, i.e. the type of index (string, long...) described by this indexer. */ public interface Indexer<T> { /** * Checks if this indexer is capable of processing (i.e. producing an indexed value for) the given object. * * <p> * This method is guaranteed to be always invoked by {@link ChronoDB} before {@link #getIndexValues(Object)} is called. If this method returns <code>false</code>, then the framework assumes that this indexer is incapable of processing this object and this indexer will be ignored for this object. * * @param object * The object which should be indexed. Must not be <code>null</code>. * @return <code>true</code> if this indexer can produce an indexed value for the given object, or <code>false</code> if the given object cannot be processed by this indexer. */ public boolean canIndex(Object object); /** * Produces the indexed values of the given object. * * <p> * This method is only called by {@link ChronoDB} if a previous call to {@link #canIndex(Object)} with the same parameter returned <code>true</code>. * * @param object * The object to index. Must not be <code>null</code>. * @return A {@link Set} of elements representing the indexed values for the given object. <code>null</code>-values in the set will be ignored. Subclasses may specify more rigid constraints on this set; please check their documentation. If this method returns <code>null</code>, it will be treated as if it had returned an empty set. */ public Set<T> getIndexValues(Object object); }
3,108
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
DoubleIndexer.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/api/indexing/DoubleIndexer.java
package org.chronos.chronodb.api.indexing; import java.util.Set; import org.chronos.chronodb.api.ChronoDB; /** * A {@link DoubleIndexer} is an {@link Indexer} capable of extracting {@link Double} values from an object. * * <p> * Please refer to the documentation in {@link Indexer} for more details. * * @author martin.haeulser@uibk.ac.at -- Initial Contribution and API */ public interface DoubleIndexer extends Indexer<Double> { /** * Produces the indexed Double values of the given object. * * <p> * This method is only called by {@link ChronoDB} if a previous call to {@link #canIndex(Object)} with the same parameter returned <code>true</code>. * * @param object * The object to index. Must not be <code>null</code>. * @return A {@link Set} of Doubles representing the indexed values for the given object. <code>null</code>-values in the set will be ignored. If this method returns <code>null</code>, it will be treated as if it had returned an empty set. */ @Override public Set<Double> getIndexValues(Object object); }
1,070
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
LongIndexer.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/api/indexing/LongIndexer.java
package org.chronos.chronodb.api.indexing; import java.util.Set; import org.chronos.chronodb.api.ChronoDB; /** * A {@link LongIndexer} is an {@link Indexer} capable of extracting {@link Long} values from an object. * * <p> * Please refer to the documentation in {@link Indexer} for more details. * * @author martin.haeulser@uibk.ac.at -- Initial Contribution and API */ public interface LongIndexer extends Indexer<Long> { /** * Produces the indexed long values of the given object. * * <p> * This method is only called by {@link ChronoDB} if a previous call to {@link #canIndex(Object)} with the same parameter returned <code>true</code>. * * @param object * The object to index. Must not be <code>null</code>. * @return A {@link Set} of longs representing the indexed values for the given object. <code>null</code>-values in the set will be ignored. If this method returns <code>null</code>, it will be treated as if it had returned an empty set. */ @Override public Set<Long> getIndexValues(Object object); }
1,055
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AtomicConflict.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/api/conflict/AtomicConflict.java
package org.chronos.chronodb.api.conflict; import org.chronos.chronodb.api.key.ChronoIdentifier; public interface AtomicConflict { public long getTransactionTimestamp(); public ChronoIdentifier getSourceKey(); public Object getSourceValue(); public ChronoIdentifier getTargetKey(); public Object getTargetValue(); public ChronoIdentifier getCommonAncestorKey(); public Object getCommonAncestorValue(); }
421
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ConflictResolutionStrategy.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/api/conflict/ConflictResolutionStrategy.java
package org.chronos.chronodb.api.conflict; import org.chronos.chronodb.internal.impl.conflict.strategies.DoNotMergeStrategy; import org.chronos.chronodb.internal.impl.conflict.strategies.OverwriteWithSourceStrategy; import org.chronos.chronodb.internal.impl.conflict.strategies.OverwriteWithTargetStrategy; public interface ConflictResolutionStrategy { // ================================================================================================================= // DEFAULT STRATEGIES // ================================================================================================================= public static ConflictResolutionStrategy OVERWRITE_WITH_SOURCE = OverwriteWithSourceStrategy.INSTANCE; public static ConflictResolutionStrategy OVERWRITE_WITH_TARGET = OverwriteWithTargetStrategy.INSTANCE; public static ConflictResolutionStrategy DO_NOT_MERGE = DoNotMergeStrategy.INSTANCE; // ================================================================================================================= // PUBLIC API // ================================================================================================================= public Object resolve(AtomicConflict conflict); }
1,215
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
QueryBuilderFinalizer.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/api/builder/query/QueryBuilderFinalizer.java
package org.chronos.chronodb.api.builder.query; import com.google.common.collect.Sets; import org.chronos.chronodb.api.key.QualifiedKey; import java.util.Collections; import java.util.Iterator; import java.util.Map.Entry; import java.util.Set; /** * Represents a final part in the query builder API, i.e. one that allows to actually execute the previously built * query. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API */ public interface QueryBuilderFinalizer { /** * Executes the previously built query. * * <p> * Usage example: * * <pre> * Iterator&lt;QualifiedKey&gt; iterator = tx.find().where("name").contains("hello").getKeys(); * </pre> * * @return An iterator over all keys that match the query. May be empty, but never <code>null</code>. */ public Iterator<QualifiedKey> getKeys(); /** * Executes the previously built query. * * <p> * Please note that this method requires to completely exhaust the result iterator. For certain backends, this might * be an expensive operation. It is recommended to use {@link #getKeys()} in favor of this method whenever possible, * as it can lazily fetch the results on-demand. * * <p> * Usage example: * * <pre> * Set&lt;QualifiedKey&gt; resultSet = tx.find().where("name").contains("hello").getKeysAsSet(); * </pre> * * @return An immutable set of all keys that match the query. May be empty, but never <code>null</code>. */ public default Set<QualifiedKey> getKeysAsSet() { Iterator<QualifiedKey> iterator = this.getKeys(); Set<QualifiedKey> resultSet = Sets.newHashSet(); while (iterator.hasNext()) { QualifiedKey key = iterator.next(); resultSet.add(key); } return Collections.unmodifiableSet(resultSet); } /** * Executes the previously built query. * * <p> * Please note that this method requires to completely exhaust the result iterator. For certain backends, this might * be an expensive operation. It is recommended to use {@link #getKeys()} in favor of this method whenever possible, * as it can lazily fetch the results on-demand. * * <p> * Usage example: * * <pre> * Set&lt;String&gt; resultSet = tx.find().where("name").contains("hello").getUnqualifiedKeysAsSet(); * </pre> * * @return An immutable set of all keys that match the query. * Note that the keyspaces are not included in the result, only the primary keys will be returned. * May be empty, but never <code>null</code>. */ public default Set<String> getUnqualifiedKeysAsSet() { Iterator<QualifiedKey> iterator = this.getKeys(); Set<String> resultSet = Sets.newHashSet(); while (iterator.hasNext()) { QualifiedKey qKey = iterator.next(); resultSet.add(qKey.getKey()); } return Collections.unmodifiableSet(resultSet); } /** * Executes the previously built query. * * <p> * Usage example: * * <pre> * Iterator&lt;Entry&lt;QualifiedKey, Object&gt;&gt; iterator = tx.find().where("name").contains("hello").getQualifiedResult(); * // now simply iterate over the result... * while (iterator.hasNext()) { * Entry&lt;QualifiedKey, Object&gt; entry = iterator.next(); * QualifiedKey qKey = entry.getKey(); * Object value = entry.getValue(); * // ... do something with them * } * </pre> * * @return An iterator over all qualified key-value pairs that match the query. May be empty, but never * <code>null</code>. */ public Iterator<Entry<QualifiedKey, Object>> getQualifiedResult(); /** * Executes the previously built query. * * <p> * Usage example: * * <pre> * Iterator&lt;Entry&lt;String, Object&gt;&gt; iterator = tx.find().where("name").contains("hello").getResult(); * // now simply iterate over the result... * while (iterator.hasNext()) { * Entry&lt;String, Object&gt; entry = iterator.next(); * String key = entry.getKey(); * Object value = entry.getValue(); * // ... do something with them * } * </pre> * * <p> * <b>WARNING:</b><br> * The result set of this method will contain <i>all</i> key-value combinations that match the query. If the query * considers more than one keyspace, then the returned keys are not guaranteed to be unique. The reason is that a * single key can simultaneously appear in multiple keyspaces with potentially different values. To disambiguate * this situation, please consider using {@link #getQualifiedResult()} if you are dealing with queries across * keyspaces. * * @return An iterator over all key-value pairs that match the query. May be empty, but never <code>null</code>. * @see #getQualifiedResult() */ public Iterator<Entry<String, Object>> getResult(); /** * Executes the previously built query. * * <p> * Usage example: * * <pre> * Iterator&lt;Object&gt; iterator = tx.find().where("name").contains("hello").getValues(); * // now simply iterate over the result... * while (iterator.hasNext()) { * Object value = iterator.next(); * // ... do something with it * } * </pre> * * <p> * <b>WARNING:</b> The returned iterator delivers the values for all key-value pairs that match the query. It is * <b>not guaranteed</b> that any of the values will be unique! * * @return An iterator over all values that match the query. May be empty, but never <code>null</code>. */ public Iterator<Object> getValues(); /** * Executes the previously built query. * * <p> * Please note that this method requires to completely exhaust the result iterator. For certain backends, this might * be an expensive operation. It is recommended to use {@link #getValues()} in favor of this method whenever * possible, as it can lazily fetch the results on-demand. * * <p> * Usage example: * * <pre> * Set&lt;Object&gt; resultSet = tx.find().where("name").contains("hello").getValuesAsSet(); * // now simply iterate over the result... * for (Object result : resultSet) { * // ... do something with it * } * </pre> * * @return An immutable set containing the objects returned by the query. May be empty, but never <code>null</code>. */ public default Set<Object> getValuesAsSet() { Iterator<Object> iterator = this.getValues(); Set<Object> resultSet = Sets.newHashSet(); while (iterator.hasNext()) { Object object = iterator.next(); resultSet.add(object); } return Collections.unmodifiableSet(resultSet); } }
6,999
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
QueryBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/api/builder/query/QueryBuilder.java
package org.chronos.chronodb.api.builder.query; /** * A fluent API for building queries in ChronoDB. * * <p> * Please see the individual methods for usage examples. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public interface QueryBuilder extends QueryBaseBuilder<QueryBuilder> { /** * Begins a "where" clause. The supplied argument is the property which will be matched. * * <p> * Usage example: * * <pre> * tx.find().where("name").isEqualTo("Martin").getResult(); * </pre> * * @param property * The property to match. Must not be <code>null</code>. * * @return The builder to specify the condition in. Never <code>null</code>. */ public WhereBuilder where(String property); }
762
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
QueryBuilderStarter.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/api/builder/query/QueryBuilderStarter.java
package org.chronos.chronodb.api.builder.query; /** * This is the initial interface that starts off the fluent query builder API. * * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public interface QueryBuilderStarter { /** * Adds a keyspace constraint. * * <p> * Without such a constraint, all keyspaces are scanned. * * <p> * Usage example: * * <pre> * tx.find().inKeyspace("MyKeyspace").where("Hello").isEqualTo("World").getResult(); * </pre> * * @param keyspace * The keyspace to scan. Must not be <code>null</code>. * * @return The builder for method chaining. */ public QueryBuilder inKeyspace(String keyspace); /** * Adds a constraint to scan only the default keyspace. * * <p> * Without such a constraint, all keyspaces are scanned. * * <p> * Usage example: * * <pre> * tx.find().inDefaultKeyspace().where("Hello").isEqualTo("World").getResult(); * </pre> * * @return The builder for method chaining. */ public QueryBuilder inDefaultKeyspace(); }
1,069
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
WhereBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/api/builder/query/WhereBuilder.java
package org.chronos.chronodb.api.builder.query; import org.chronos.chronodb.internal.impl.query.TextMatchMode; import java.util.Set; import java.util.regex.Pattern; /** * This interface is a part of the fluent query API for ChronoDB. * * <p> * It allows to specify a variety of conditions in a "where" clause. * * <p> * Please see the individual methods for examples. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public interface WhereBuilder { // ================================================================================================================= // STRING OPERATIONS // ================================================================================================================= /** * Adds a text containment constraint. * * <p> * Usage example: * * <pre> * tx.find().where("name").contains("Martin").getResult(); * </pre> * * * @param text * The text to search for. Must not be <code>null</code> or empty. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder contains(String text); /** * Adds a case-insensitive text containment constraint. * * <p> * Usage example: * * <pre> * tx.find().where("name").containsIgnoreCase("martin").getResult(); * </pre> * * * @param text * The text to search for. Must not be <code>null</code> or empty. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder containsIgnoreCase(String text); /** * Adds a text not-containment constraint. * * <p> * Usage example: * * <pre> * tx.find().where("name").notContains("Martin").getResult(); * </pre> * * * @param text * The text to search for. Must not be <code>null</code> or empty. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder notContains(String text); /** * Adds a case-insensitive text not-containment constraint. * * <p> * Usage example: * * <pre> * tx.find().where("name").notContainsIgnoreCase("martin").getResult(); * </pre> * * * @param text * The text to search for. Must not be <code>null</code> or empty. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder notContainsIgnoreCase(String text); /** * Adds a text "starts with" constraint. * * <p> * Usage example: * * <pre> * tx.find().where("name").startsWith("Ma").getResult(); * </pre> * * * @param text * The text to search for. Must not be <code>null</code> or empty. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder startsWith(String text); /** * Adds a case-insensitive text "starts with" constraint. * * <p> * Usage example: * * <pre> * tx.find().where("name").startsWithIgnoreCase("ma").getResult(); * </pre> * * * @param text * The text to search for. Must not be <code>null</code> or empty. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder startsWithIgnoreCase(String text); /** * Adds a text "not starts with" constraint. * * <p> * Usage example: * * <pre> * tx.find().where("name").notStartsWith("Ma").getResult(); * </pre> * * * @param text * The text to search for. Must not be <code>null</code> or empty. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder notStartsWith(String text); /** * Adds a case-insensitive text "not starts with" constraint. * * <p> * Usage example: * * <pre> * tx.find().where("name").notStartsWithIgnoreCase("ma").getResult(); * </pre> * * * @param text * The text to search for. Must not be <code>null</code> or empty. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder notStartsWithIgnoreCase(String text); /** * Adds a text "ends with" constraint. * * <p> * Usage example: * * <pre> * tx.find().where("name").endsWith("rtin").getResult(); * </pre> * * * @param text * The text to search for. Must not be <code>null</code> or empty. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder endsWith(String text); /** * Adds a case-insensitive text "ends with" constraint. * * <p> * Usage example: * * <pre> * tx.find().where("name").endsWithIgnoreCase("rtin").getResult(); * </pre> * * * @param text * The text to search for. Must not be <code>null</code> or empty. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder endsWithIgnoreCase(String text); /** * Adds a text "not ends with" constraint. * * <p> * Usage example: * * <pre> * tx.find().where("name").notEndsWith("rtin").getResult(); * </pre> * * * @param text * The text to search for. Must not be <code>null</code> or empty. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder notEndsWith(String text); /** * Adds a case-insensitive text "not ends with" constraint. * * <p> * Usage example: * * <pre> * tx.find().where("name").notEndsWithIgnoreCase("rtin").getResult(); * </pre> * * * @param text * The text to search for. Must not be <code>null</code> or empty. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder notEndsWithIgnoreCase(String text); /** * Adds a regex constraint. * * <p> * Usage example: * * <pre> * tx.find().where("name").matchesRegex("He(ll)*o").getResult(); * </pre> * * * @param regex * The regex to search for. Must not be <code>null</code> or empty. Supports the full range of expressions defined in <code>java.util.regex.</code>{@link Pattern}. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder matchesRegex(String regex); /** * Adds a negated regex constraint. * * <p> * Usage example: * * <pre> * tx.find().where("name").notMatchesRegex("He(ll)*o").getResult(); * </pre> * * * @param regex * The regex to search for. Must not be <code>null</code> or empty. Supports the full range of expressions defined in <code>java.util.regex.</code>{@link Pattern}. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder notMatchesRegex(String regex); /** * Adds a case-insensitive regex constraint. * * <p> * Usage example: * * <pre> * tx.find().where("name").matchesRegexIgnoreCase("He(ll)*o").getResult(); * </pre> * * * @param regex * The regex to search for. Must not be <code>null</code> or empty. Supports the full range of expressions defined in <code>java.util.regex.</code>{@link Pattern}. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder matchesRegexIgnoreCase(String regex); /** * Adds a case-insensitive, negated regex constraint. * * <p> * Usage example: * * <pre> * tx.find().where("name").notMatchesRegexIgnoreCase("He(ll)*o").getResult(); * </pre> * * * @param regex * The regex to search for. Must not be <code>null</code> or empty. Supports the full range of expressions defined in <code>java.util.regex.</code>{@link Pattern}. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder notMatchesRegexIgnoreCase(String regex); /** * Adds a text equality constraint. * * <p> * Usage example: * * <pre> * tx.find().where("name").isEqualTo("Martin").getResult(); * </pre> * * * @param value * The text to search for. Must not be <code>null</code> or empty. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder isEqualTo(String value); /** * Adds a case-insensitive text equality constraint. * * <p> * Usage example: * * <pre> * tx.find().where("name").isEqualToIgnoreCase("martin").getResult(); * </pre> * * * @param value * The text to search for. Must not be <code>null</code> or empty. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder isEqualToIgnoreCase(String value); /** * Adds a negated text equality constraint. * * <p> * Usage example: * * <pre> * tx.find().where("name").isNotEqualTo("Martin").getResult(); * </pre> * * * @param value * The text to search for. Must not be <code>null</code> or empty. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder isNotEqualTo(String value); /** * Adds a case-insensitive negated text equality constraint. * * <p> * Usage example: * * <pre> * tx.find().where("name").isNotEqualToIgnoreCase("Martin").getResult(); * </pre> * * * @param value * The text to search for. Must not be <code>null</code> or empty. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder isNotEqualToIgnoreCase(String value); // ================================================================================================================= // LONG OPERATIONS // ================================================================================================================= /** * Adds a long equality constraint. * * <p> * Usage example: * * <pre> * tx.find().where("height").isEqualTo(8000).getResult(); * </pre> * * * @param value * The value to compare against. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder isEqualTo(long value); /** * Adds a negated long equality constraint. * * <p> * Usage example: * * <pre> * tx.find().where(height).isNotEqualTo(8000).getResult(); * </pre> * * * @param value * The value to compare against. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder isNotEqualTo(long value); /** * Adds a "greater than" ( <code>&gt</code> ) constraint. * * <p> * Usage example: * * <pre> * tx.find().where(height).isGreaterThan(8000).getResult(); * </pre> * * @param value * The value to compare against. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder isGreaterThan(long value); /** * Adds a "greater than or equal to" ( <code>&gt=</code> ) constraint. * * <p> * Usage example: * * <pre> * tx.find().where(height).isGreaterThanOrEqualTo(8000).getResult(); * </pre> * * @param value * The value to compare against. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder isGreaterThanOrEqualTo(long value); /** * Adds a "less than" ( <code>&lt</code> ) constraint. * * <p> * Usage example: * * <pre> * tx.find().where(height).isLessThan(8000).getResult(); * </pre> * * @param value * The value to compare against. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder isLessThan(long value); /** * Adds a "less than or equal to" ( <code>&lt=</code> ) constraint. * * <p> * Usage example: * * <pre> * tx.find().where(height).isLessThanOrEqualTo(8000).getResult(); * </pre> * * @param value * The value to compare against. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder isLessThanOrEqualTo(long value); // ================================================================================================================= // DOUBLE OPERATIONS // ================================================================================================================= /** * Adds a long equality constraint. * * <p> * Usage example: * * <pre> * tx.find().where("height").isEqualTo(1.75, 0.01).getResult(); * </pre> * * * @param value * The value to compare against. * @param tolerance * The allowed tolerance range for equality checks. Will be applied in positive AND negative direction. Must not be negative. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder isEqualTo(double value, double tolerance); /** * Adds a negated long equality constraint. * * <p> * Usage example: * * <pre> * tx.find().where(height).isNotEqualTo(1.75, 0.01).getResult(); * </pre> * * * @param value * The value to compare against. * @param tolerance * The allowed tolerance range for equality checks. Will be applied in positive AND negative direction. Must not be negative. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder isNotEqualTo(double value, double tolerance); /** * Adds a "greater than" ( <code>&gt</code> ) constraint. * * <p> * Usage example: * * <pre> * tx.find().where(height).isGreaterThan(1.75).getResult(); * </pre> * * @param value * The value to compare against. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder isGreaterThan(double value); /** * Adds a "greater than or equal to" ( <code>&gt=</code> ) constraint. * * <p> * Usage example: * * <pre> * tx.find().where(height).isGreaterThanOrEqualTo(1.75).getResult(); * </pre> * * @param value * The value to compare against. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder isGreaterThanOrEqualTo(double value); /** * Adds a "less than" ( <code>&lt</code> ) constraint. * * <p> * Usage example: * * <pre> * tx.find().where(height).isLessThan(1.75).getResult(); * </pre> * * @param value * The value to compare against. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder isLessThan(double value); /** * Adds a "less than or equal to" ( <code>&lt=</code> ) constraint. * * <p> * Usage example: * * <pre> * tx.find().where(height).isLessThanOrEqualTo(1.75).getResult(); * </pre> * * @param value * The value to compare against. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder isLessThanOrEqualTo(double value); // ================================================================================================================= // SET OPERATIONS // ================================================================================================================= /** * Adds a contained-in-set-constraint, the strings are compared with equalsIgnoreCase * * <p> * Usage example: * * <pre> * tx.find().where("name").inStringsIgnoreCase(Sets.newHashSet("John", "Jane")).getResult(); * </pre> * * * @param values * The set containing the values to compare against. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder inStringsIgnoreCase(Set<String> values); /** * Adds a contained-in-set-constraint, the strings are strictly compared with equals * * <p> * Usage example: * * <pre> * tx.find().where("name").inStrings(Sets.newHashSet("John", "Jane")).getResult(); * </pre> * * * @param values * The set containing the values to compare against. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder inStrings(Set<String> values); /** * Adds a not-contained-in-set-constraint, the strings are compared with equalsIgnoreCase * * <p> * Usage example: * * <pre> * tx.find().where("name").notInStringsIgnoreCase(Sets.newHashSet("John", "Jane")).getResult(); * </pre> * * * @param values * The set containing the values to compare against. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder notInStringsIgnoreCase(Set<String> values); /** * Adds a not-contained-in-set-constraint, the strings are strictly compared with equals * * <p> * Usage example: * * <pre> * tx.find().where("name").notInStrings(Sets.newHashSet("John", "Jane")).getResult(); * </pre> * * * @param values * The set containing the values to compare against. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder notInStrings(Set<String> values); /** * Adds a contained-in-set-constraint. * * <p> * Usage example: * * <pre> * tx.find().where(height).inLongs(Sets.newHashSet(8000, 4000)).getResult(); * </pre> * * @param values * The values to compare against. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder inLongs(Set<Long> values); /** * Adds a not-contained-in-set-constraint. * * <p> * Usage example: * * <pre> * tx.find().where(height).notInLongs(Sets.newHashSet(8000, 4000)).getResult(); * </pre> * * @param values * The values to compare against. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder notInLongs(Set<Long> values); /** * Adds a contained-in-set-constraint. * * <p> * Usage example: * * <pre> * tx.find().where(height).inDoubles(Sets.newHashSet(8000.3, 4000.5)).getResult(); * </pre> * * @param values * The values to compare against. * @param tolerance * The allowed tolerance range for equality checks. Will be applied in positive AND negative direction. Must not be negative. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder inDoubles(Set<Double> values, double tolerance); /** * Adds a not-contained-in-set-constraint. * * <p> * Usage example: * * <pre> * tx.find().where(height).notInDoubles(Sets.newHashSet(8000.3, 4000.5)).getResult(); * </pre> * * @param values * The values to compare against. * @param tolerance * The allowed tolerance range for equality checks. Will be applied in positive AND negative direction. Must not be negative. * * @return The next builder. Never <code>null</code>. */ public FinalizableQueryBuilder notInDoubles(Set<Double> values, double tolerance); }
18,661
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
QueryBaseBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/api/builder/query/QueryBaseBuilder.java
package org.chronos.chronodb.api.builder.query; /** * A base interface for the fluent {@link QueryBuilder} API. * * <p> * Specifies a couple of methods several builders have in common. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * * @param <SELF> * The dynamic type of <code>this</code> to return for method chaining. */ public interface QueryBaseBuilder<SELF extends QueryBaseBuilder<?>> { /** * Encapsulates the following expressions in a <code>begin</code>-<code>end</code> brace. * * <p> * This is useful for deciding the precedence of the <code>and</code> and <code>or</code> operators. * * <p> * Usage example: * * <pre> * tx.find().begin().where("name").contains("Hello").or().where("name").contains("World").end().and().where("age") * .isGreaterThanOrEqualTo(1000).getResult(); * </pre> * * @return <code>this</code> for method chaining */ public SELF begin(); /** * Terminates the encapsulation of the preceding expressions in a <code>begin</code>-<code>end</code> brace. * * <p> * This is useful for deciding the precedence of the <code>and</code> and <code>or</code> operators. * * <p> * Usage example: * * <pre> * tx.find().begin().where("name").contains("Hello").or().where("name").contains("World").end().and().where("name") * .notContains("foo").getResult(); * </pre> * * @return <code>this</code> for method chaining */ public SELF end(); /** * Negates the following expressions. * * <p> * Usage example: * * <pre> * tx.find().not().where("name").contains("Hello").getResult(); * </pre> * * @return <code>this</code> for method chaining */ public SELF not(); }
1,722
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
FinalizableQueryBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/api/builder/query/FinalizableQueryBuilder.java
package org.chronos.chronodb.api.builder.query; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.internal.api.query.ChronoDBQuery; /** * Represents the (potentially) last step in the fluent query API. * * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public interface FinalizableQueryBuilder extends QueryBaseBuilder<FinalizableQueryBuilder>, QueryBuilderFinalizer { /** * Returns the previously built query, in a stand-alone format. * * <p> * The returned query is independent of the transaction and consequently independent of the transaction timestamp. This method should be used when the result of a query at different timestamps is of interest. The resulting query can be executed via {@link ChronoDBTransaction#find(ChronoDBQuery)}. * * @return The built query. Never <code>null</code>. */ public ChronoDBQuery toQuery(); /** * Executes the previously built query, returning the count of matching elements. * * <p> * Usage example: * * <pre> * long resultCount = tx.find().where("name").contains("hello").count(); * </pre> * * @return The count of keys matching the query. Never negative. */ public long count(); /** * Extends the query by adding a logical "and" operator. * * @return The next builder for method chaining. Never <code>null</code>. */ public QueryBuilder and(); /** * Extends the query by adding a logical "or" operator. * * @return The next builder for method chaining. Never <code>null</code>. */ public QueryBuilder or(); }
1,581
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoDBTransactionBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/api/builder/transaction/ChronoDBTransactionBuilder.java
package org.chronos.chronodb.api.builder.transaction; import static com.google.common.base.Preconditions.*; import java.util.Date; import org.chronos.chronodb.api.Branch; 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; /** * This class represents a fluid builder API for the configuration and creation of {@link ChronoDBTransaction} * instances. * * <p> * This class is intended to be used in a fluent way. For example: * * <pre> * ChronoDB chronoDB = ...; // get some ChronoDB instance * ChronoDBTransaction transaction = chronoDB.txBuilder().onBranch("MyBranch").readOnly().buildLRU(); * // ... now do something with the transaction * </pre> * * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public interface ChronoDBTransactionBuilder { /** * Builds the {@link ChronoDBTransaction} based on the configuration in this builder. * * @return The {@link ChronoDBTransaction}. Never <code>null</code>. */ public ChronoDBTransaction build(); /** * Enables read-only mode on this transaction. * * <p> * Transactions in read-only mode will refuse any modifying operations, such as * {@link ChronoDBTransaction#put(String, Object)} or {@link ChronoDBTransaction#remove(String)}. * * @return The builder (<code>this</code>) for method chaining. Never <code>null</code>. */ public ChronoDBTransactionBuilder readOnly(); /** * Enables thread-safety on this transaction. * * <p> * Please note that {@link ChronoDB} is capable of handling concurrent transactions. This setting only controls how * one single transaction behaves under concurrent access. By default, one transaction is intended for one thread * and thus not thread-safe. This method enables a thread-safe mode for a single transaction, which synchronizes the * internal state appropriately. Do not use this unless it is absolutely required, as performance on non-thread-safe * transactions is likely better than on thread-safe ones. * * @return The builder (<code>this</code>) for method chaining. Never <code>null</code>. */ public ChronoDBTransactionBuilder threadSafe(); /** * Sets up the transaction to read the contents of the {@link ChronoDB} instance at the given date. * * <p> * Please note that this method writes to the same internal value as {@link #atTimestamp(long)}. They are * semantically equivalent. The last write access to occur before {@link #build()} wins. * * @param date * The date to use for the read timestamp. Must not be <code>null</code>. * * @return The builder (<code>this</code>) for method chaining. Never <code>null</code>. */ public ChronoDBTransactionBuilder atDate(Date date); /** * Sets up the transaction to read the contents of the {@link ChronoDB} instance at the given timestamp. * * <p> * Please note that this method writes to the same internal value as {@link #atDate(Date)}. They are semantically * equivalent. The last write access to occur before {@link #build()} wins. * * @param timestamp * The timestamp to use for read access. Must not be <code>null</code>. * * @return The builder (<code>this</code>) for method chaining. Never <code>null</code>. */ public ChronoDBTransactionBuilder atTimestamp(long timestamp); /** * Sets the name of the {@link ChronoDB} branch to read in this transaction. * * <p> * By default, this value is set to read the <code>master</code> branch (see: * {@link ChronoDBConstants#MASTER_BRANCH_IDENTIFIER}). * * @param branchName * The name of the branch to connect to. Must not be <code>null</code>. Must refer to an existing branch. * * @return The builder (<code>this</code>) for method chaining. Never <code>null</code>. */ public ChronoDBTransactionBuilder onBranch(String branchName); /** * Sets the {@link Branch} to read from or write to in this transaction. * * <p> * By default, this is set to the master branch. * * @param branch * The branch to connect to. Must not be <code>null</code>. Must refer to an existing branch. * * @return The builder (<code>this</code>) for method chaining. Never <code>null</code>. */ public default ChronoDBTransactionBuilder onBranch(final Branch branch) { checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); return this.onBranch(branch.getName()); } /** * Sets the given {@link ConflictResolutionStrategy} for this transaction (overriding the database default). * * * @param strategy * The strategy to use for this transaction. Must not be <code>null</code>. * @return The builder (<code>this</code>) for method chaining. Never <code>null</code>. */ public ChronoDBTransactionBuilder withConflictResolutionStrategy(ConflictResolutionStrategy strategy); /** * Enables or disables duplicate version elimination on the constructed transaction. * * <p> * By default, this value is set to the duplicate version elimination setting of the {@link ChronoDB} instance to * which the transaction connects. This method allows to override the database instance defaults for a single * transaction. * * @param mode * The duplicate version elimination mode to use for this transaction only. Must not be <code>null</code> * . * * @return The builder (<code>this</code>) for method chaining. Never <code>null</code>. */ public ChronoDBTransactionBuilder withDuplicateVersionEliminationMode(DuplicateVersionEliminationMode mode); }
5,786
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoDBBackendBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/api/builder/database/ChronoDBBackendBuilder.java
package org.chronos.chronodb.api.builder.database; /** * Marker interface for all builders of ChronoDB backends. Used for type safety. * * @author martin.haeusler@uibk.ac.at -- initial contribution and API. * */ public interface ChronoDBBackendBuilder { }
262
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoDBPropertyFileBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/api/builder/database/ChronoDBPropertyFileBuilder.java
package org.chronos.chronodb.api.builder.database; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.internal.impl.ChronoDBBaseConfiguration; /** * A builder for all kinds of instances of {@link ChronoDB}, based on a <code>*.properties</code> file. * * <p> * The resulting {@link ChronoDB} implementation is determined via the value of the * {@link ChronoDBBaseConfiguration#getBackendType()} property. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public interface ChronoDBPropertyFileBuilder extends ChronoDBFinalizableBuilder<ChronoDBPropertyFileBuilder> { }
624
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoDBBaseBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/api/builder/database/ChronoDBBaseBuilder.java
package org.chronos.chronodb.api.builder.database; import org.apache.commons.configuration2.Configuration; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.internal.api.ChronoDBConfiguration; import java.io.File; import java.util.Properties; /** * This is the starter interface for building a {@link ChronoDB} interface in a fluent API. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public interface ChronoDBBaseBuilder { /** * Loads the given file as a {@link Properties} file, and assigns it to a provider. * <p> * <p> * For details on the possible configurations, please refer to {@linkplain ChronoDBConfiguration the configuration * API}. * * @param file The file to load. Must exist, must be a file, must not be <code>null</code>. * @return The provider to continue configuration with, with the properties from the given file loaded. Never * <code>null</code>. */ public ChronoDBPropertyFileBuilder fromPropertiesFile(File file); /** * Loads the given file path as a {@link Properties} file, and assigns it to a provider. * <p> * <p> * For details on the possible configurations, please refer to {@linkplain ChronoDBConfiguration the configuration * API}. * * @param filePath The file path to load. Must exist, must be a file, must not be <code>null</code>. * @return The provider to continue configuration with, with the properties from the given file loaded. Never * <code>null</code>. */ public ChronoDBPropertyFileBuilder fromPropertiesFile(String filePath); /** * Loads the given Apache {@link Configuration} object and assigns it to a provider. * <p> * <p> * For details on the possible configurations, please refer to {@linkplain ChronoDBConfiguration the configuration * API}. * * @param configuration The configuration data to load. Must not be <code>null</code>. * @return The provider to continue configuration with, with the properties from the configuration loaded. Never * <code>null</code>. */ public ChronoDBPropertyFileBuilder fromConfiguration(Configuration configuration); /** * Loads the given {@link java.util.Properties} object and assigns it to a provider. * <p> * <p> * For details on the possible configurations, please refer to {@linkplain ChronoDBConfiguration the configuration * API}. * * @param properties The properties to load. Must not be <code>null</code>. * @return The provider to continue configuration with, with the given properties loaded. Never <code>null</code>. */ public ChronoDBPropertyFileBuilder fromProperties(Properties properties); /** * Creates a new database instance using the given provider class. * * <p> * For example, to create an in-memory database, use: * * <pre> * ChronoDB inMemoryDB = ChronoDB.FACTORY.create().database(InMemoryChronoDB.BUILDER).build() * </pre> * </p> * * @param builderClass The provider class to use. Please refer to the documentation of your backend to find the correct class. Must not be <code>null</code>. * @param <T> The provider type produced by the given class. * @return The provider to continue configuration with, never <code>null</code>. */ public <T extends ChronoDBBackendBuilder> T database(Class<T> builderClass); }
3,332
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoDBFinalizableBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/api/builder/database/ChronoDBFinalizableBuilder.java
package org.chronos.chronodb.api.builder.database; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.CommitMetadataFilter; import org.chronos.chronodb.api.conflict.ConflictResolutionStrategy; import org.chronos.chronodb.internal.api.ChronoDBConfiguration; import org.chronos.common.builder.ChronoBuilder; /** * A builder for instances of {@link ChronoDB}. * * <p> * When an instance of this interface is returned by the fluent builder API, then all information required for building * the database is complete, and {@link #build()} can be called to finalize the buildLRU process. * * <p> * Even though the {@link #build()} method becomes available at this stage, it is still possible to set properties * defined by the concrete implementations. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * * @param <SELF> * The dynamic type of <code>this</code> to return for method chaining. */ public interface ChronoDBFinalizableBuilder<SELF extends ChronoDBFinalizableBuilder<?>> extends ChronoBuilder<SELF> { /** * Enables Least-Recently-Used caching on the new {@link ChronoDB} instance. * * <p> * If this operation is called several times on the same builder instance, the last setting wins. * * @param maxSize * The maximum number of elements to be contained in the LRU cache. If this number is less than or equal * to zero, the caching is disabled instead. * * @return <code>this</code>, for method chaining. */ public SELF withLruCacheOfSize(int maxSize); /** * Enables or disables the assumption that values in the cache of this {@link ChronoDB} instance are immutable. * * <p> * By default, this is set to <code>false</code>. Enabling this setting can greatly increase the speed of the cache, * however cache state may be corrupted if cached values are changed by client code. This setting is only viable if * the client ensures that the objects passed to the key-value store are effectively immutable. * * @param value * Set this to <code>true</code> to enable the assumption that cached value objects are immutable * (optimistic, faster, see above), otherwise use <code>false</code> (pessimistic, default). * * @return <code>this</code>, for method chaining. */ public SELF assumeCachedValuesAreImmutable(boolean value); /** * Enables Least-Recently-Used caching on the new {@link ChronoDB} instance for query results. * * @param maxSize * The maximum number of elements to be contained in the LRU Query Result Cache. If this number is less * than or equal to zero, the caching is disabled instead. * * @return <code>this</code>, for method chaining. */ public SELF withLruQueryCacheOfSize(int maxSize); /** * Enables or disables duplicate version elimination on commit. * * <p> * If this is enabled, every changed key-value pair will be checked for identity with the previous version. * Key-value pairs that are identical to their predecessors will be filtered out and will not be committed. This * does not alter the semantics of the store in any way, but it eliminates the duplicates, reducing overall store * size on disk and enhancing read performance. * * <p> * This setting is enabled by default and it is recommended to keep this setting enabled, unless the caller can * guarantee that each version is different from the predecessor. In general, this feature will cause some overhead * on the {@linkplain ChronoDBTransaction#commit() commit} operation. * * <p> * Corresponds to {@link ChronoDBConfiguration#DUPLICATE_VERSION_ELIMINATION_MODE}. * * @param useDuplicateVersionElimination * <code>true</code> to enable this feature, or <code>false</code> to disable it. Default is * <code>true</code>. * @return <code>this</code>, for method chaining. */ public SELF withDuplicateVersionElimination(final boolean useDuplicateVersionElimination); /** * Specifies the {@link ConflictResolutionStrategy} to use for this database by default. * * <p> * This setting can be overruled on a per-transaction basis. * * @param strategy * The strategy to apply, unless specified otherwise explicitly in a transaction. Must not be * <code>null</code>. * @return <code>this</code>, for method chaining. */ public SELF withConflictResolutionStrategy(final ConflictResolutionStrategy strategy); /** * Specifies the {@link CommitMetadataFilter} to use for this database. * * @param filterClass The filter class to use. May be <code>null</code> to specify "no filter" (default). Otherwise, must be a class instantiable via reflection. * @return <code>this</code>, for method chaining. */ public SELF withCommitMetadataFilter(final Class<? extends CommitMetadataFilter> filterClass); /** * Builds the {@link ChronoDB} instance, using the properties specified by the fluent API. * * <p> * This method finalizes the buildLRU process. Afterwards, the builder should be discarded. * * @return The new {@link ChronoDB} instance. Never <code>null</code>. */ public ChronoDB build(); }
5,279
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
TestSuitePlugin.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/api/builder/database/spi/TestSuitePlugin.java
package org.chronos.chronodb.api.builder.database.spi; import org.apache.commons.configuration2.Configuration; import org.chronos.common.exceptions.ChronosIOException; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.nio.file.Files; import java.nio.file.Path; import java.util.UUID; public interface TestSuitePlugin { public Configuration createBasicTestConfiguration(Method testMethod, File testDirectory); public void onBeforeTest(Class<?> testClass, Method testMethod, File testDirectory); public void onAfterTest(Class<?> testClass, Method testMethod, File testDirectory); public default File createFileDBFile(File testDirectory) { File dbFile = new File(testDirectory, UUID.randomUUID().toString().replaceAll("-", "") + ".chronodb"); try { Path path = dbFile.toPath(); Files.deleteIfExists(path); Files.createFile(path); } catch (IOException e) { throw new ChronosIOException("Failed to create DB file in test directory '" + testDirectory.getAbsolutePath() + "'!"); } return dbFile; } }
1,152
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoDBBackendProvider.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/api/builder/database/spi/ChronoDBBackendProvider.java
package org.chronos.chronodb.api.builder.database.spi; import org.apache.commons.configuration2.Configuration; import org.chronos.chronodb.api.builder.database.ChronoDBBackendBuilder; import org.chronos.chronodb.internal.api.ChronoDBConfiguration; import org.chronos.chronodb.internal.api.ChronoDBInternal; public interface ChronoDBBackendProvider { public boolean matchesBackendName(String backendName); public Class<? extends ChronoDBConfiguration> getConfigurationClass(); public ChronoDBInternal instantiateChronoDB(Configuration configuration); public String getBackendName(); public TestSuitePlugin getTestSuitePlugin(); public ChronoDBBackendBuilder createBuilder(); }
709
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
InMemoryDatebackManager.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/inmemory/InMemoryDatebackManager.java
package org.chronos.chronodb.inmemory; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.chronos.chronodb.internal.api.ChronoDBInternal; import org.chronos.chronodb.internal.impl.dateback.AbstractDatebackManager; import org.chronos.chronodb.internal.api.dateback.log.DatebackOperation; import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.TreeMap; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.*; public class InMemoryDatebackManager extends AbstractDatebackManager { private static final Comparator<LogKey> COMPARATOR = Comparator.comparing(LogKey::getBranch).thenComparing(LogKey::getTimestamp).thenComparing(LogKey::getId); private final TreeMap<LogKey, DatebackOperation> map = Maps.newTreeMap(COMPARATOR); public InMemoryDatebackManager(final ChronoDBInternal dbInstance) { super(dbInstance); } @Override protected void writeDatebackOperationToLog(final DatebackOperation operation) { checkNotNull(operation, "Precondition violation - argument 'operation' must not be NULL!"); LogKey logKey = new LogKey(operation); this.map.put(logKey, operation); } @Override public List<DatebackOperation> getAllPerformedDatebackOperations() { return Lists.newArrayList(this.map.values()); } @Override protected List<DatebackOperation> getDatebackOperationsPerformedOnBranchBetween(final String branch, final long dateTimeMin, final long dateTimeMax) { return Lists.newArrayList(this.map.subMap(new LogKey(branch, dateTimeMin, ""), true, new LogKey(branch, dateTimeMax + 1, ""), true).values()); } @Override public void deleteLogsForBranch(final String name) { List<LogKey> keys = this.map.keySet().stream().filter(key -> Objects.equals(key.getBranch(), name)).collect(Collectors.toList()); for(LogKey key : keys){ this.map.remove(key); } } private static class LogKey { private final String branch; private final long timestamp; private final String id; public LogKey(String branch, long timestamp, String id) { this.branch = branch; this.timestamp = timestamp; this.id = id; } public LogKey(DatebackOperation operation) { this.branch = operation.getBranch(); this.timestamp = operation.getWallClockTime(); this.id = operation.getId(); } public String getBranch() { return branch; } public long getTimestamp() { return timestamp; } public String getId() { return this.id; } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LogKey logKey = (LogKey) o; return id != null ? id.equals(logKey.id) : logKey.id == null; } @Override public int hashCode() { return id != null ? id.hashCode() : 0; } } }
3,228
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
InMemoryStatisticsManager.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/inmemory/InMemoryStatisticsManager.java
package org.chronos.chronodb.inmemory; import com.google.common.collect.Maps; import org.chronos.chronodb.api.BranchHeadStatistics; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.internal.api.BranchInternal; import org.chronos.chronodb.internal.api.ChronoDBInternal; import org.chronos.chronodb.internal.impl.engines.base.AbstractStatisticsManager; import java.util.Map; import static com.google.common.base.Preconditions.*; public class InMemoryStatisticsManager extends AbstractStatisticsManager { private final ChronoDBInternal owningDB; private final Map<String, BranchHeadStatistics> branchHeadStatistics = Maps.newHashMap(); public InMemoryStatisticsManager(ChronoDBInternal owningDB){ checkNotNull(owningDB, "Precondition violation - argument 'owningDB' must not be NULL!"); this.owningDB = owningDB; } @Override protected BranchHeadStatistics loadBranchHeadStatistics(final String branch) { BranchHeadStatistics statistics = this.branchHeadStatistics.get(branch); if(statistics == null){ BranchInternal b = this.owningDB.getBranchManager().getBranch(branch); if(b == null){ throw new IllegalArgumentException("There is no branch named '" + branch + "'!"); } statistics = b.getTemporalKeyValueStore().calculateBranchHeadStatistics(); this.branchHeadStatistics.put(branch, statistics); } return statistics; } @Override protected void saveBranchHeadStatistics(final String branchName, final BranchHeadStatistics statistics) { this.branchHeadStatistics.put(branchName, statistics); } @Override public void deleteBranchHeadStatistics() { this.branchHeadStatistics.clear(); } @Override public void deleteBranchHeadStatistics(final String branchName) { checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!"); this.branchHeadStatistics.remove(branchName); } }
2,051
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
InMemoryCommitMetadataStore.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/inmemory/InMemoryCommitMetadataStore.java
package org.chronos.chronodb.inmemory; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.chronos.chronodb.api.Branch; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.Order; import org.chronos.chronodb.internal.impl.engines.base.AbstractCommitMetadataStore; import org.chronos.chronodb.internal.impl.engines.base.ChronosInternalCommitMetadata; import org.chronos.chronodb.internal.util.NavigableMapUtils; import org.chronos.common.exceptions.UnknownEnumLiteralException; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import java.util.NavigableMap; import java.util.concurrent.ConcurrentSkipListMap; import static com.google.common.base.Preconditions.*; public class InMemoryCommitMetadataStore extends AbstractCommitMetadataStore { private NavigableMap<Long, byte[]> commitMetadataMap; public InMemoryCommitMetadataStore(final ChronoDB owningDB, final Branch owningBranch) { super(owningDB, owningBranch); this.commitMetadataMap = new ConcurrentSkipListMap<>(); } @Override protected byte[] getInternal(final long timestamp) { checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); return this.commitMetadataMap.get(timestamp); } @Override protected void putInternal(final long commitTimestamp, final byte[] serializedMetadata) { checkArgument(commitTimestamp >= 0, "Precondition violation - argument 'commitTimestamp' must not be negative!"); checkNotNull(serializedMetadata, "Precondition violation - argument 'serializedMetadata' must not be NULL!"); this.commitMetadataMap.put(commitTimestamp, serializedMetadata); } @Override protected void rollbackToTimestampInternal(final long timestamp) { checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); NavigableMap<Long, byte[]> subMap = this.commitMetadataMap.subMap(timestamp, false, Long.MAX_VALUE, true); subMap.clear(); } @Override public boolean purge(final long commitTimestamp) { if (this.commitMetadataMap.containsKey(commitTimestamp) == false) { return false; } this.commitMetadataMap.remove(commitTimestamp); return true; } @Override public Iterator<Long> getCommitTimestampsBetween(final long from, final long to, final Order order, boolean includeSystemInternalCommits) { checkArgument(from >= 0, "Precondition violation - argument 'from' must not be negative!"); checkArgument(to >= 0, "Precondition violation - argument 'to' must not be negative!"); checkNotNull(order, "Precondition violation - argument 'order' must not be NULL!"); // fail-fast if the period is empty if (from > to) { return Collections.emptyIterator(); } NavigableMap<Long, byte[]> subMap = this.commitMetadataMap.subMap(from, true, to, true); if (!includeSystemInternalCommits) { // apply filter subMap = Maps.filterValues(subMap, this::isBinaryUserCommitMetadata); } switch (order) { case ASCENDING: // note: NavigableMap#keySet() and #entrySet() are sorted in ascending order by default. return Iterators.unmodifiableIterator(subMap.keySet().iterator()); case DESCENDING: return Iterators.unmodifiableIterator(subMap.descendingKeySet().iterator()); default: throw new UnknownEnumLiteralException(order); } } @Override public Iterator<Entry<Long, Object>> getCommitMetadataBetween(final long from, final long to, final Order order, boolean includeSystemInternalCommits) { checkArgument(from >= 0, "Precondition violation - argument 'from' must not be negative!"); checkArgument(to >= 0, "Precondition violation - argument 'to' must not be negative!"); checkNotNull(order, "Precondition violation - argument 'order' must not be NULL!"); // fail-fast if the period is empty if (from > to) { return Collections.emptyIterator(); } NavigableMap<Long, byte[]> subMap = this.commitMetadataMap.subMap(from, true, to, true); final Iterator<Entry<Long, byte[]>> rawIterator; switch (order) { case ASCENDING: rawIterator = subMap.entrySet().iterator(); break; case DESCENDING: rawIterator = subMap.descendingMap().entrySet().iterator(); break; default: throw new UnknownEnumLiteralException(order); } Iterator<Entry<Long, Object>> iterator = Iterators.transform(rawIterator, this::mapSerialEntryToPair); if (!includeSystemInternalCommits) { iterator = Iterators.filter(iterator, this::isUserCommit); } return Iterators.unmodifiableIterator(iterator); } @Override public Iterator<Long> getCommitTimestampsPaged(final long minTimestamp, final long maxTimestamp, final int pageSize, final int pageIndex, final Order order, final boolean includeSystemInternalCommits) { checkArgument(minTimestamp >= 0, "Precondition violation - argument 'minTimestamp' must not be negative!"); checkArgument(maxTimestamp >= 0, "Precondition violation - argument 'maxTimestamp' must not be negative!"); checkArgument(pageSize > 0, "Precondition violation - argument 'pageSize' must be greater than zero!"); checkArgument(pageIndex >= 0, "Precondition violation - argument 'pageIndex' must not be negative!"); checkNotNull(order, "Precondition violation - argument 'order' must not be NULL!"); // fail-fast if the period is empty if (minTimestamp > maxTimestamp) { return Collections.emptyIterator(); } int elementsToSkip = pageSize * pageIndex; NavigableMap<Long, byte[]> subMap = this.commitMetadataMap.subMap(minTimestamp, true, maxTimestamp, true); if (!includeSystemInternalCommits) { // apply filter subMap = Maps.filterValues(subMap, this::isBinaryUserCommitMetadata); } final Iterator<Long> rawIterator; switch (order) { case ASCENDING: rawIterator = subMap.keySet().iterator(); break; case DESCENDING: rawIterator = subMap.descendingKeySet().iterator(); break; default: throw new UnknownEnumLiteralException(order); } // skip entries of the iterator to arrive at the correct page for (int i = 0; i < elementsToSkip && rawIterator.hasNext(); i++) { rawIterator.next(); } // limit the rest of the iterator to the given page size return Iterators.unmodifiableIterator(Iterators.limit(rawIterator, pageSize)); } @Override public Iterator<Entry<Long, Object>> getCommitMetadataPaged(final long minTimestamp, final long maxTimestamp, final int pageSize, final int pageIndex, final Order order, final boolean includeSystemInternalCommits) { checkArgument(minTimestamp >= 0, "Precondition violation - argument 'minTimestamp' must not be negative!"); checkArgument(maxTimestamp >= 0, "Precondition violation - argument 'maxTimestamp' must not be negative!"); checkArgument(pageSize > 0, "Precondition violation - argument 'pageSize' must be greater than zero!"); checkArgument(pageIndex >= 0, "Precondition violation - argument 'pageIndex' must not be negative!"); checkNotNull(order, "Precondition violation - argument 'order' must not be NULL!"); // fail-fast if the period is empty if (minTimestamp > maxTimestamp) { return Collections.emptyIterator(); } int elementsToSkip = pageSize * pageIndex; NavigableMap<Long, byte[]> subMap = this.commitMetadataMap.subMap(minTimestamp, true, maxTimestamp, true); if (!includeSystemInternalCommits) { // apply filter subMap = Maps.filterValues(subMap, this::isBinaryUserCommitMetadata); } final Iterator<Entry<Long, byte[]>> rawIterator; switch (order) { case ASCENDING: rawIterator = subMap.entrySet().iterator(); break; case DESCENDING: rawIterator = subMap.descendingMap().entrySet().iterator(); break; default: throw new UnknownEnumLiteralException(order); } // skip entries of the iterator to arrive at the correct page for (int i = 0; i < elementsToSkip && rawIterator.hasNext(); i++) { rawIterator.next(); } // convert the serialized commit metadata objects into their Object representation Iterator<Entry<Long, Object>> iterator = Iterators.transform(rawIterator, this::mapSerialEntryToPair); // limit the rest of the iterator to the given page size return Iterators.unmodifiableIterator(Iterators.limit(iterator, pageSize)); } @Override public List<Entry<Long, Object>> getCommitMetadataAround(final long timestamp, final int count, final boolean includeSystemInternalCommits) { checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); checkArgument(count >= 0, "Precondition violation - argument 'count' must not be negative!"); NavigableMap<Long, byte[]> map = this.commitMetadataMap; if (!includeSystemInternalCommits) { // apply a filter on the map map = Maps.filterValues(map, this::isBinaryUserCommitMetadata); } List<Entry<Long, byte[]>> entriesAround = NavigableMapUtils.entriesAround(map, timestamp, count); List<Entry<Long, Object>> resultList = Lists.newArrayList(); entriesAround.forEach(e -> resultList.add(this.deserializeValueOf(e))); resultList.sort(EntryTimestampComparator.INSTANCE.reversed()); return resultList; } @Override public List<Entry<Long, Object>> getCommitMetadataBefore(final long timestamp, final int count, final boolean includeSytemInternalCommits) { checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); checkArgument(count >= 0, "Precondition violation - argument 'count' must not be negative!"); NavigableMap<Long, byte[]> map = this.commitMetadataMap.headMap(timestamp, false).descendingMap(); List<Entry<Long, Object>> resultList = Lists.newArrayList(); for (Entry<Long, byte[]> entry : map.entrySet()) { if (resultList.size() >= count) { break; } Entry<Long, Object> deserialized = this.deserializeValueOf(entry); if (includeSytemInternalCommits || isUserCommit(deserialized)) { resultList.add(deserialized); } } return resultList; } @Override public List<Entry<Long, Object>> getCommitMetadataAfter(final long timestamp, final int count, final boolean includeSystemInternalCommits) { checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); checkArgument(count >= 0, "Precondition violation - argument 'count' must not be negative!"); NavigableMap<Long, byte[]> map = this.commitMetadataMap.tailMap(timestamp, false); List<Entry<Long, Object>> resultList = Lists.newArrayList(); for (Entry<Long, byte[]> entry : map.entrySet()) { if (resultList.size() >= count) { break; } Entry<Long, Object> deserialized = this.deserializeValueOf(entry); if (includeSystemInternalCommits || isUserCommit(deserialized)) { resultList.add(deserialized); } } // navigablemaps are sorted in ascending order, we want descending return Lists.reverse(resultList); } @Override public int countCommitTimestampsBetween(final long from, final long to, final boolean includeSystemInternalCommits) { checkArgument(from >= 0, "Precondition violation - argument 'from' must not be negative!"); checkArgument(to >= 0, "Precondition violation - argument 'to' must not be negative!"); // fail-fast if the period is empty if (from >= to) { return 0; } NavigableMap<Long, byte[]> subMap = this.commitMetadataMap.subMap(from, true, to, true); if (includeSystemInternalCommits) { return subMap.size(); } else { // apply filter return (int) subMap.entrySet().stream().filter(this::isBinaryUserCommit).count(); } } @Override public int countCommitTimestamps(final boolean includeSystemInternalCommits) { if (includeSystemInternalCommits) { return this.commitMetadataMap.size(); } else { // apply filter return (int) this.commitMetadataMap.entrySet().stream() .filter(this::isBinaryUserCommit) .count(); } } // ================================================================================================================= // HELPER METHODS // ================================================================================================================= private boolean isBinaryUserCommit(Entry<Long, byte[]> entry) { return isUserCommit(this.deserializeValueOf(entry)); } private boolean isUserCommit(Entry<Long, Object> entry) { return isUserCommitMetadata(entry.getValue()); } private boolean isBinaryUserCommitMetadata(final byte[] metadata) { if (metadata == null) { return true; } return isUserCommitMetadata(this.deserialize(metadata)); } private boolean isUserCommitMetadata(final Object commitMetadata) { return !(commitMetadata instanceof ChronosInternalCommitMetadata); } }
14,524
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
TemporalInMemoryMatrix.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/inmemory/TemporalInMemoryMatrix.java
package org.chronos.chronodb.inmemory; import com.google.common.collect.Iterators; import com.google.common.collect.Sets; import org.chronos.chronodb.api.Order; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.api.key.TemporalKey; import org.chronos.chronodb.internal.api.GetResult; import org.chronos.chronodb.internal.api.Period; import org.chronos.chronodb.internal.api.stream.CloseableIterator; import org.chronos.chronodb.internal.impl.engines.base.AbstractTemporalDataMatrix; import org.chronos.chronodb.internal.impl.stream.AbstractCloseableIterator; import org.chronos.chronodb.internal.impl.temporal.InverseUnqualifiedTemporalKey; import org.chronos.chronodb.internal.impl.temporal.UnqualifiedTemporalEntry; import org.chronos.chronodb.internal.impl.temporal.UnqualifiedTemporalKey; import org.chronos.chronodb.internal.util.KeySetModifications; import org.chronos.common.exceptions.UnknownEnumLiteralException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.ConcurrentSkipListMap; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.*; public class TemporalInMemoryMatrix extends AbstractTemporalDataMatrix { private static final Logger log = LoggerFactory.getLogger(TemporalInMemoryMatrix.class); // ================================================================================================================= // FIELDS // ================================================================================================================= private final NavigableMap<UnqualifiedTemporalKey, byte[]> contents; private final NavigableMap<InverseUnqualifiedTemporalKey, Boolean> inverseContents; // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= public TemporalInMemoryMatrix(final String keyspace, final long timestamp) { super(keyspace, timestamp); this.contents = new ConcurrentSkipListMap<>(); this.inverseContents = new ConcurrentSkipListMap<>(); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public GetResult<byte[]> get(final long timestamp, final String key) { checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); QualifiedKey qKey = QualifiedKey.create(this.getKeyspace(), key); UnqualifiedTemporalKey temporalKey = UnqualifiedTemporalKey.create(key, timestamp); Entry<UnqualifiedTemporalKey, byte[]> floorEntry = this.contents.floorEntry(temporalKey); Entry<UnqualifiedTemporalKey, byte[]> ceilEntry = this.contents.higherEntry(temporalKey); if (floorEntry == null || floorEntry.getKey().getKey().equals(key) == false) { // we have no "next lower" bound -> we already know that the result will be empty. // now we need to check if we have an upper bound for the validity of our empty result... if (ceilEntry == null || ceilEntry.getKey().getKey().equals(key) == false) { // there is no value for this key (at all, not at any timestamp) return GetResult.createNoValueResult(qKey, Period.eternal()); } else if (ceilEntry != null && ceilEntry.getKey().getKey().equals(key)) { // there is no value for this key, until a certain timestamp is reached Period period = Period.createRange(0, ceilEntry.getKey().getTimestamp()); return GetResult.createNoValueResult(qKey, period); } } else { // we have a "next lower" bound -> we already know that the result will be non-empty. // now we need to check if we have an upper bound for the validity of our result... if (ceilEntry == null || ceilEntry.getKey().getKey().equals(key) == false) { // there is no further value for this key, therefore we have an open-ended period Period range = Period.createOpenEndedRange(floorEntry.getKey().getTimestamp()); byte[] value = floorEntry.getValue(); if (value != null && value.length <= 0) { // value is non-null, but empty -> it's effectively null value = null; } return GetResult.create(qKey, value, range); } else if (ceilEntry != null && ceilEntry.getKey().getKey().equals(key)) { // the value of the result is valid between the floor and ceiling entries Period period = Period.createRange(floorEntry.getKey().getTimestamp(), ceilEntry.getKey().getTimestamp()); byte[] value = floorEntry.getValue(); if (value != null && value.length <= 0) { // value is non-null, but empty -> it's effectively null value = null; } return GetResult.create(qKey, value, period); } } // this code is effectively unreachable throw new RuntimeException("Unreachable code has been reached!"); } @Override public void put(final long time, final Map<String, byte[]> contents) { checkArgument(time >= 0, "Precondition violation - argument 'time' must not be negative!"); checkNotNull(contents, "Precondition violation - argument 'contents' must not be NULL!"); if(contents.isEmpty()){ return; } this.ensureCreationTimestampIsGreaterThanOrEqualTo(time); for (Entry<String, byte[]> entry : contents.entrySet()) { String key = entry.getKey(); byte[] value = entry.getValue(); UnqualifiedTemporalKey tk = UnqualifiedTemporalKey.create(key, time); if (value != null) { if(log.isTraceEnabled()){ log.trace("[PUT] " + tk + "bytes[" + value.length + "]"); } this.contents.put(tk, value); } else { this.contents.put(tk, new byte[0]); if(log.isTraceEnabled()){ log.trace("[PUT] " + tk + "NULL"); } } InverseUnqualifiedTemporalKey itk = InverseUnqualifiedTemporalKey.create(time, key); if (value != null) { this.inverseContents.put(itk, true); } else { this.inverseContents.put(itk, false); } } } @Override public KeySetModifications keySetModifications(final long timestamp) { checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); // entry set is sorted in ascending order! Set<Entry<UnqualifiedTemporalKey, byte[]>> entrySet = this.contents.entrySet(); Set<String> additions = Sets.newHashSet(); Set<String> removals = Sets.newHashSet(); // iterate over the full B-Tree key set (ascending order) Iterator<Entry<UnqualifiedTemporalKey, byte[]>> allEntriesIterator = entrySet.iterator(); while (allEntriesIterator.hasNext()) { Entry<UnqualifiedTemporalKey, byte[]> currentEntry = allEntriesIterator.next(); UnqualifiedTemporalKey currentKey = currentEntry.getKey(); if (currentKey.getTimestamp() > timestamp) { continue; } String plainKey = currentKey.getKey(); if (currentEntry.getValue() == null || currentEntry.getValue().length <= 0) { // removal additions.remove(plainKey); removals.add(plainKey); } else { // put additions.add(plainKey); removals.remove(plainKey); } } return new KeySetModifications(additions, removals); } @Override public Iterator<Long> history(final String key, final long lowerBound, final long upperBound, final Order order) { checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); checkArgument(lowerBound >= 0, "Precondition violation - argument 'lowerBound' must not be negative!"); checkArgument(upperBound >= 0, "Precondition violation - argument 'upperBound' must not be negative!"); checkArgument(lowerBound <= upperBound, "Precondition violation - argument 'lowerBound' must be less than or equal to argument 'upperBound'!"); checkNotNull(order, "Precondition violation - argument 'order' must not be NULL!"); UnqualifiedTemporalKey tkMin = UnqualifiedTemporalKey.create(key, lowerBound); UnqualifiedTemporalKey tkMax = UnqualifiedTemporalKey.create(key, upperBound); NavigableMap<UnqualifiedTemporalKey, byte[]> subMap = this.contents.subMap(tkMin, true, tkMax, true); final Iterator<UnqualifiedTemporalKey> iterator; switch(order){ case ASCENDING: iterator = subMap.keySet().iterator(); break; case DESCENDING: iterator = subMap.descendingKeySet().iterator(); break; default: throw new UnknownEnumLiteralException(order); } return new ChangeTimesIterator(iterator); } @Override public long lastCommitTimestamp(final String key, final long upperBound) { checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); checkArgument( upperBound >= 0, "Precondition violation - argument 'upperBound' must not be negative!"); UnqualifiedTemporalKey floorKey = this.contents.floorKey(UnqualifiedTemporalKey.create(key, upperBound)); if(floorKey == null || !floorKey.getKey().equals(key)){ // has never been modified return -1; }else{ return floorKey.getTimestamp(); } } @Override public void insertEntries(final Set<UnqualifiedTemporalEntry> entries, final boolean force) { checkNotNull(entries, "Precondition violation - argument 'entries' must not be NULL!"); if(entries.isEmpty()){ return; } // update the creation timestamp in case that at least one of the entries is in the past long minTimestamp = entries.stream().mapToLong(entry -> entry.getKey().getTimestamp()).min().orElse(-1); if(minTimestamp > 0){ this.ensureCreationTimestampIsGreaterThanOrEqualTo(minTimestamp); } // update primary index for (UnqualifiedTemporalEntry entry : entries) { UnqualifiedTemporalKey key = entry.getKey(); byte[] value = entry.getValue(); this.contents.put(key, value); } // update inverse index for (UnqualifiedTemporalEntry entry : entries) { String key = entry.getKey().getKey(); long timestamp = entry.getKey().getTimestamp(); InverseUnqualifiedTemporalKey itk = InverseUnqualifiedTemporalKey.create(timestamp, key); this.inverseContents.put(itk, entry.getValue() != null); } } @Override public CloseableIterator<UnqualifiedTemporalEntry> allEntriesIterator(final long minTimestamp, final long maxTimestamp) { return new AllEntriesIterator(this.contents.entrySet().iterator(), minTimestamp, maxTimestamp); } @Override public void rollback(final long timestamp) { Iterator<Entry<UnqualifiedTemporalKey, byte[]>> iterator = this.contents.entrySet().iterator(); while (iterator.hasNext()) { Entry<UnqualifiedTemporalKey, byte[]> entry = iterator.next(); if (entry.getKey().getTimestamp() > timestamp) { iterator.remove(); } } Iterator<Entry<InverseUnqualifiedTemporalKey, Boolean>> iterator2 = this.inverseContents.entrySet().iterator(); while (iterator2.hasNext()) { Entry<InverseUnqualifiedTemporalKey, Boolean> entry = iterator2.next(); if (entry.getKey().getTimestamp() > timestamp) { iterator2.remove(); } } } @Override public Iterator<TemporalKey> getModificationsBetween(final long timestampLowerBound, final long timestampUpperBound) { checkArgument(timestampLowerBound >= 0, "Precondition violation - argument 'timestampLowerBound' must not be negative!"); checkArgument(timestampUpperBound >= 0, "Precondition violation - argument 'timestampUpperBound' must not be negative!"); checkArgument(timestampLowerBound <= timestampUpperBound, "Precondition violation - argument 'timestampLowerBound' must be less than or equal to 'timestampUpperBound'!"); InverseUnqualifiedTemporalKey itkLow = InverseUnqualifiedTemporalKey.createMinInclusive(timestampLowerBound); InverseUnqualifiedTemporalKey itkHigh = InverseUnqualifiedTemporalKey.createMaxExclusive(timestampUpperBound); NavigableMap<InverseUnqualifiedTemporalKey, Boolean> subMap = this.inverseContents.subMap(itkLow, true, itkHigh, false); Iterator<InverseUnqualifiedTemporalKey> iterator = subMap.keySet().iterator(); return Iterators.transform(iterator, itk -> TemporalKey.create(itk.getTimestamp(), this.getKeyspace(), itk.getKey())); } @Override public int purgeEntries(final Set<UnqualifiedTemporalKey> keys) { checkNotNull(keys, "Precondition violation - argument 'keys' must not be NULL!"); int successfullyPurged = 0; for(UnqualifiedTemporalKey utk : keys){ if (this.contents.containsKey(utk) == false) { continue; } this.contents.remove(utk); this.inverseContents.remove(utk.inverse()); successfullyPurged++; } return successfullyPurged; } @Override public Set<UnqualifiedTemporalKey> purgeAllEntriesInTimeRange(final long purgeRangeStart, final long purgeRangeEnd) { NavigableMap<InverseUnqualifiedTemporalKey, Boolean> subMap = this.inverseContents.subMap( InverseUnqualifiedTemporalKey.create(purgeRangeStart, ""), true, InverseUnqualifiedTemporalKey.create(purgeRangeEnd + 1, ""), false ); Set<UnqualifiedTemporalKey> inverseUnqualifiedTemporalKeys = subMap.keySet().stream() .filter(iutk -> iutk.getTimestamp() >= purgeRangeStart && iutk.getTimestamp() <= purgeRangeEnd) .map(InverseUnqualifiedTemporalKey::inverse) .collect(Collectors.toSet()); inverseUnqualifiedTemporalKeys.forEach(utk -> { this.inverseContents.remove(utk.inverse()); this.contents.remove(utk); }); return inverseUnqualifiedTemporalKeys; } @Override public long size() { return this.contents.size(); } @Override public void ensureCreationTimestampIsGreaterThanOrEqualTo(long timestamp) { checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); if(this.getCreationTimestamp() > timestamp){ this.setCreationTimestamp(timestamp); } } // ================================================================================================================= // INNER CLASSES // ================================================================================================================= private static class ChangeTimesIterator implements Iterator<Long> { private final Iterator<UnqualifiedTemporalKey> keyIterator; public ChangeTimesIterator(final Iterator<UnqualifiedTemporalKey> keyIterator) { this.keyIterator = keyIterator; } @Override public boolean hasNext() { return this.keyIterator.hasNext(); } @Override public Long next() { return this.keyIterator.next().getTimestamp(); } } private static class AllEntriesIterator extends AbstractCloseableIterator<UnqualifiedTemporalEntry> { private final Iterator<Entry<UnqualifiedTemporalKey, byte[]>> entryIterator; public AllEntriesIterator(final Iterator<Entry<UnqualifiedTemporalKey, byte[]>> entryIterator, final long minTimestamp, final long maxTimestamp) { this.entryIterator = Iterators.filter(entryIterator, entry ->{ long timestamp = entry.getKey().getTimestamp(); return timestamp >= minTimestamp && timestamp <= maxTimestamp; }); } @Override protected boolean hasNextInternal() { return this.entryIterator.hasNext(); } @Override public UnqualifiedTemporalEntry next() { Entry<UnqualifiedTemporalKey, byte[]> entry = this.entryIterator.next(); UnqualifiedTemporalKey key = entry.getKey(); byte[] value = entry.getValue(); return new UnqualifiedTemporalEntry(key, value); } @Override protected void closeInternal() { // nothing to do for an in-memory matrix. } } }
17,844
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
InMemoryMaintenanceManager.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/inmemory/InMemoryMaintenanceManager.java
package org.chronos.chronodb.inmemory; import org.chronos.chronodb.api.MaintenanceManager; import java.util.function.Predicate; import static com.google.common.base.Preconditions.*; public class InMemoryMaintenanceManager implements MaintenanceManager { @SuppressWarnings("unused") private final InMemoryChronoDB owningDB; public InMemoryMaintenanceManager(final InMemoryChronoDB owningDB) { checkNotNull(owningDB, "Precondition violation - argument 'owningDB' must not be NULL!"); this.owningDB = owningDB; } // ================================================================================================================= // ROLLOVER // ================================================================================================================= @Override public void performRolloverOnBranch(final String branchName, boolean updateIndices) { throw new UnsupportedOperationException("The in-memory backend does not support rollover operations."); } @Override public void performRolloverOnAllBranches(boolean updateIndices) { throw new UnsupportedOperationException("The in-memory backend does not support rollover operations."); } @Override public void performRolloverOnAllBranchesWhere(final Predicate<String> branchPredicate, boolean updateIndices) { throw new UnsupportedOperationException("The in-memory backend does not support rollover operations."); } }
1,485
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
IndexEntry.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/inmemory/IndexEntry.java
package org.chronos.chronodb.inmemory; import org.chronos.chronodb.api.TextCompare; import org.chronos.chronodb.internal.api.Period; import org.jetbrains.annotations.NotNull; import java.util.Collections; import java.util.Comparator; import java.util.List; import static com.google.common.base.Preconditions.*; public class IndexEntry implements Comparable<IndexEntry> { public static Comparator<IndexEntry> createComparator(TextCompare textCompare) { return (o1, 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 { return textCompare.apply(o1.getKey()).compareTo(textCompare.apply(o2.getKey())); } }; } private final IndexKey key; private final List<Period> validPeriods; public IndexEntry(IndexKey key, List<Period> validPeriods) { checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); checkNotNull(validPeriods, "Precondition violation - argument 'validPeriods' must not be NULL!"); this.key = key; this.validPeriods = Collections.unmodifiableList(validPeriods); } public IndexKey getKey() { return key; } public List<Period> getValidPeriods() { return validPeriods; } @Override public int compareTo(@NotNull final IndexEntry o) { return this.getKey().compareTo(o.getKey()); } @Override public String toString() { return "IndexEntry{key=" + key + ", validPeriods=" + validPeriods + '}'; } }
1,707
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
InMemorySerializationManager.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/inmemory/InMemorySerializationManager.java
package org.chronos.chronodb.inmemory; import org.chronos.chronodb.api.SerializationManager; import org.chronos.common.serialization.KryoManager; public class InMemorySerializationManager implements SerializationManager { public InMemorySerializationManager() { } @Override public byte[] serialize(final Object object) { return KryoManager.serialize(object); } @Override public Object deserialize(final byte[] serialForm) { return KryoManager.deserialize(serialForm); } }
526
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
IndexKey.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/inmemory/IndexKey.java
package org.chronos.chronodb.inmemory; import org.jetbrains.annotations.NotNull; import static com.google.common.base.Preconditions.*; public class IndexKey implements Comparable<IndexKey> { private final Comparable<?> indexValue; private final String key; public IndexKey(@NotNull Comparable<?> indexValue, @NotNull String key) { checkNotNull(indexValue, "Precondition violation - argument 'indexValue' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); this.indexValue = indexValue; this.key = key; } public Comparable<?> getIndexValue() { return indexValue; } public String getKey() { return key; } @Override public String toString() { return "IndexKey{indexValue=" + indexValue + ", key='" + key + "'}"; } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; IndexKey indexKey = (IndexKey) o; if (!indexValue.equals(indexKey.indexValue)) return false; return key.equals(indexKey.key); } @Override public int hashCode() { int result = indexValue.hashCode(); result = 31 * result + key.hashCode(); return result; } @Override @SuppressWarnings({"unchecked", "rawtypes"}) public int compareTo(@NotNull final IndexKey o) { int indexValueComparison = ((Comparable)this.indexValue).compareTo(o.getIndexValue()); if(indexValueComparison != 0){ return indexValueComparison; } return this.key.compareTo(o.getKey()); } }
1,745
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
InMemoryFeatures.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/inmemory/InMemoryFeatures.java
package org.chronos.chronodb.inmemory; import org.chronos.chronodb.api.ChronoDBFeatures; public class InMemoryFeatures implements ChronoDBFeatures { @Override public boolean isPersistent() { return false; } @Override public boolean isRolloverSupported() { return false; } @Override public boolean isIncrementalBackupSupported() { return false; } }
414
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
InMemoryChronoDB.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/inmemory/InMemoryChronoDB.java
package org.chronos.chronodb.inmemory; import org.chronos.chronodb.api.*; import org.chronos.chronodb.inmemory.builder.ChronoDBInMemoryBuilder; import org.chronos.chronodb.inmemory.builder.ChronoDBInMemoryBuilderImpl; import org.chronos.chronodb.internal.api.BranchManagerInternal; import org.chronos.chronodb.internal.api.ChronoDBConfiguration; import org.chronos.chronodb.internal.api.DatebackManagerInternal; import org.chronos.chronodb.internal.api.StatisticsManagerInternal; import org.chronos.chronodb.internal.api.cache.ChronoDBCache; import org.chronos.chronodb.internal.api.index.IndexManagerInternal; import org.chronos.chronodb.internal.api.query.QueryManager; import org.chronos.chronodb.internal.impl.engines.base.AbstractChronoDB; import org.chronos.chronodb.internal.impl.index.DocumentBasedIndexManager; import org.chronos.chronodb.internal.impl.query.StandardQueryManager; import org.chronos.common.version.ChronosVersion; import static com.google.common.base.Preconditions.*; public class InMemoryChronoDB extends AbstractChronoDB { // ================================================================================================================= // CONSTANTS // ================================================================================================================= public static final String BACKEND_NAME = "inmemory"; public static final Class<? extends ChronoDBInMemoryBuilder> BUILDER = ChronoDBInMemoryBuilderImpl.class; // ================================================================================================================= // FIELDS // ================================================================================================================= private final InMemoryBranchManager branchManager; private final InMemorySerializationManager serializationManager; private final IndexManagerInternal indexManager; private final StandardQueryManager queryManager; private final InMemoryMaintenanceManager maintenanceManager; private final DatebackManagerInternal datebackManager; private final InMemoryStatisticsManager statisticsManager; private final BackupManager backupManager; private final ChronoDBCache cache; // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= public InMemoryChronoDB(final ChronoDBConfiguration configuration) { super(configuration); this.branchManager = new InMemoryBranchManager(this); this.serializationManager = new InMemorySerializationManager(); this.queryManager = new StandardQueryManager(this); this.indexManager = new DocumentBasedIndexManager(this); this.maintenanceManager = new InMemoryMaintenanceManager(this); this.datebackManager = new InMemoryDatebackManager(this); this.statisticsManager = new InMemoryStatisticsManager(this); this.backupManager = new InMemoryBackupManager(this); this.cache = ChronoDBCache.createCacheForConfiguration(configuration); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public BranchManagerInternal getBranchManager() { return this.branchManager; } @Override public SerializationManager getSerializationManager() { return this.serializationManager; } @Override public QueryManager getQueryManager() { return this.queryManager; } @Override public IndexManagerInternal getIndexManager() { return this.indexManager; } @Override public MaintenanceManager getMaintenanceManager() { return this.maintenanceManager; } @Override public StatisticsManagerInternal getStatisticsManager(){ return this.statisticsManager; } @Override public DatebackManagerInternal getDatebackManager() { return this.datebackManager; } @Override public BackupManager getBackupManager() { return backupManager; } @Override public ChronoDBCache getCache() { return this.cache; } @Override public boolean isFileBased() { return false; } @Override public void updateChronosVersionTo(final ChronosVersion chronosVersion) { checkNotNull(chronosVersion, "Precondition violation - argument 'chronosVersion' must not be NULL!"); // we can safely ignore this; in-memory DBs never need to be migrated. } @Override public ChronosVersion getStoredChronosVersion() { // well, we don't have any other possibility here, really... return ChronosVersion.getCurrentVersion(); } @Override public ChronoDBFeatures getFeatures() { return new InMemoryFeatures(); } // ===================================================================================================================== // INTERNAL METHODS // ===================================================================================================================== @Override public boolean requiresAutoReindexAfterDumpRead() { return true; } @Override protected ChronosVersion updateBuildVersionInDatabase(boolean readOnly) { // this isn't applicable for in-memory databases because the chronos build version // can never change during a live JVM session. return ChronosVersion.getCurrentVersion(); } }
5,801
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
InMemoryTKVS.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/inmemory/InMemoryTKVS.java
package org.chronos.chronodb.inmemory; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.internal.api.*; import org.chronos.chronodb.internal.impl.engines.base.AbstractTemporalKeyValueStore; import org.chronos.chronodb.internal.impl.engines.base.WriteAheadLogToken; import java.util.concurrent.atomic.AtomicLong; import static com.google.common.base.Preconditions.*; public class InMemoryTKVS extends AbstractTemporalKeyValueStore implements TemporalKeyValueStore { // ================================================================================================================= // FIELDS // ================================================================================================================= private final AtomicLong now = new AtomicLong(0); private final CommitMetadataStore commitMetadataStore; private WriteAheadLogToken walToken = null; // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= public InMemoryTKVS(final ChronoDBInternal db, final BranchInternal branch) { super(db, branch); this.commitMetadataStore = new InMemoryCommitMetadataStore(db, branch); TemporalDataMatrix matrix = this.createMatrix(ChronoDBConstants.DEFAULT_KEYSPACE_NAME, 0L); this.keyspaceToMatrix.put(ChronoDBConstants.DEFAULT_KEYSPACE_NAME, matrix); } // ================================================================================================================= // INTERNAL API // ================================================================================================================= @Override protected long getNowInternal() { return this.now.get(); } @Override protected void setNow(final long timestamp) { this.now.set(timestamp); } @Override protected TemporalDataMatrix createMatrix(final String keyspace, final long timestamp) { checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); return new TemporalInMemoryMatrix(keyspace, timestamp); } @Override protected synchronized void performWriteAheadLog(final WriteAheadLogToken token) { checkNotNull(token, "Precondition violation - argument 'token' must not be NULL!"); this.walToken = token; } @Override protected synchronized void clearWriteAheadLogToken() { this.walToken = null; } @Override public void performStartupRecoveryIfRequired() { // startup recovery is never needed for in-memory elements } @Override protected synchronized WriteAheadLogToken getWriteAheadLogTokenIfExists() { return this.walToken; } @Override public CommitMetadataStore getCommitMetadataStore() { return this.commitMetadataStore; } }
3,141
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
InMemoryBackupManager.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/inmemory/InMemoryBackupManager.java
package org.chronos.chronodb.inmemory; import org.chronos.chronodb.api.dump.IncrementalBackupResult; import org.chronos.chronodb.internal.impl.engines.base.AbstractBackupManager; import java.io.File; import java.util.List; public class InMemoryBackupManager extends AbstractBackupManager { public InMemoryBackupManager(final InMemoryChronoDB db) { super(db); } @Override public IncrementalBackupResult createIncrementalBackup(final long minTimestamp, final long lastRequestWallClockTime) { throw new UnsupportedOperationException("The in-memory backend does not support incremental backups. Use full backups instead."); } @Override public void loadIncrementalBackups(final List<File> cibFiles) { throw new UnsupportedOperationException("The in-memory backend does not support incremental backups. Use full backups instead."); } }
892
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
InMemoryChronoDBConfiguration.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/inmemory/InMemoryChronoDBConfiguration.java
package org.chronos.chronodb.inmemory; import org.chronos.chronodb.internal.impl.ChronoDBBaseConfiguration; public class InMemoryChronoDBConfiguration extends ChronoDBBaseConfiguration { }
192
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
InMemoryBranchManager.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/inmemory/InMemoryBranchManager.java
package org.chronos.chronodb.inmemory; import com.google.common.collect.Sets; import org.chronos.chronodb.api.Branch; import org.chronos.chronodb.api.ChronoDBConstants; 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.TemporalKeyValueStore; import org.chronos.chronodb.internal.impl.BranchImpl; import org.chronos.chronodb.internal.impl.IBranchMetadata; import org.chronos.chronodb.internal.impl.engines.base.AbstractBranchManager; import org.chronos.chronodb.internal.impl.engines.base.BranchDirectoryNameResolver; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import static com.google.common.base.Preconditions.*; public class InMemoryBranchManager extends AbstractBranchManager { // ================================================================================================================= // FIELDS // ================================================================================================================= private final ChronoDBInternal owningDb; private final Map<String, BranchInternal> branchNameToBranch = new ConcurrentHashMap<>(); // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= public InMemoryBranchManager(final ChronoDBInternal db) { super(BranchDirectoryNameResolver.NULL_NAME_RESOLVER); checkNotNull(db, "Precondition violation - argument 'db' must not be NULL!"); this.owningDb = db; this.createMasterBranch(); } // ===================================================================================================================== // PUBLIC API // ===================================================================================================================== @Override public Set<String> getBranchNames() { return Collections.unmodifiableSet(Sets.newHashSet(this.branchNameToBranch.keySet())); } // ===================================================================================================================== // INTERNAL HELPER METHODS // ===================================================================================================================== @Override protected BranchInternal getBranchInternal(final String name) { return this.branchNameToBranch.get(name); } @Override protected BranchInternal createBranch(final IBranchMetadata metadata) { checkNotNull(metadata, "Precondition violation - argument 'metadata' must not be NULL!"); BranchInternal branch = BranchImpl.createBranch(metadata, this.getBranch(metadata.getParentName())); this.createTKVS(branch); this.branchNameToBranch.put(branch.getName(), branch); return branch; } protected BranchInternal createMasterBranch() { BranchImpl masterBranch = BranchImpl.createMasterBranch(); this.createTKVS(masterBranch); this.branchNameToBranch.put(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, masterBranch); return masterBranch; } protected TemporalKeyValueStore createTKVS(final BranchInternal branch) { checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); return new InMemoryTKVS(this.owningDb, branch); } @Override protected void deleteSingleBranch(final Branch branch) { this.branchNameToBranch.remove(branch.getName()); DatebackManagerInternal datebackManager = this.owningDb.getDatebackManager(); datebackManager.deleteLogsForBranch(branch.getName()); } @Override public ChronoDBInternal getOwningDB() { return owningDb; } }
4,052
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
InMemoryIndexManagerBackend.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/inmemory/InMemoryIndexManagerBackend.java
package org.chronos.chronodb.inmemory; import com.google.common.collect.*; import org.chronos.chronodb.api.Branch; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.Order; import org.chronos.chronodb.api.SecondaryIndex; import org.chronos.chronodb.api.TextCompare; import org.chronos.chronodb.api.key.ChronoIdentifier; import org.chronos.chronodb.internal.api.ChronoDBInternal; import org.chronos.chronodb.internal.api.Period; import org.chronos.chronodb.internal.api.index.*; import org.chronos.chronodb.internal.api.query.searchspec.SearchSpecification; import org.chronos.chronodb.internal.impl.engines.base.AbstractDocumentBasedIndexManagerBackend; import org.chronos.chronodb.internal.impl.index.AbstractIndexManager; import org.chronos.chronodb.internal.impl.index.SecondaryIndexImpl; import org.chronos.chronodb.internal.impl.index.cursor.BasicIndexScanCursor; import org.chronos.chronodb.internal.impl.index.cursor.DeltaResolvingScanCursor; import org.chronos.chronodb.internal.impl.index.cursor.IndexScanCursor; import org.chronos.chronodb.internal.impl.index.cursor.RawIndexCursor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.*; public class InMemoryIndexManagerBackend extends AbstractDocumentBasedIndexManagerBackend { private static final Logger log = LoggerFactory.getLogger(InMemoryIndexManagerBackend.class); /** * Index -> Index Documents */ protected final SetMultimap<SecondaryIndex, ChronoIndexDocument> indexToDocuments; /** * Index -> Keyspace Name -> Key -> Index Documents */ protected final Map<SecondaryIndex, Map<String, SetMultimap<String, ChronoIndexDocument>>> documents; /** * Index name -> indexers */ protected final Set<SecondaryIndexImpl> allIndices = Sets.newHashSet(); // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= public InMemoryIndexManagerBackend(final ChronoDBInternal owningDB) { super(owningDB); this.indexToDocuments = HashMultimap.create(); this.documents = Maps.newHashMap(); } // ================================================================================================================= // INDEXER MANAGEMENT // ================================================================================================================= public Set<SecondaryIndexImpl> loadIndexersFromPersistence() { return Collections.unmodifiableSet(this.allIndices); } public void persistIndexers(final Set<SecondaryIndexImpl> indices) { this.allIndices.clear(); this.allIndices.addAll(indices); } @Override public void deleteAllIndexContents() { this.documents.clear(); this.indexToDocuments.clear(); } public void deleteAllIndicesAndIndexers() { this.allIndices.clear(); this.documents.clear(); this.indexToDocuments.clear(); } @Override public void deleteIndexContents(final SecondaryIndex index) { this.documents.remove(index); this.indexToDocuments.removeAll(index); } public void deleteIndexContentsAndIndex(final SecondaryIndex index) { this.deleteIndexContents(index); this.allIndices.remove((SecondaryIndexImpl) index); } public void persistIndex(final SecondaryIndexImpl index) { this.allIndices.add(index); } // ================================================================================================================= // INDEX DOCUMENT MANAGEMENT // ================================================================================================================= @Override public void applyModifications(final ChronoIndexDocumentModifications indexModifications) { checkNotNull(indexModifications, "Precondition violation - argument 'indexModifications' must not be NULL!"); if (indexModifications.isEmpty()) { return; } if (log.isTraceEnabled()) { log.trace("Applying index modifications: " + indexModifications); } for (DocumentValidityTermination termination : indexModifications.getDocumentValidityTerminations()) { ChronoIndexDocument document = termination.getDocument(); long timestamp = termination.getTerminationTimestamp(); this.terminateDocumentValidity(document, timestamp); } for (DocumentAddition creation : indexModifications.getDocumentCreations()) { ChronoIndexDocument document = creation.getDocumentToAdd(); this.addDocument(document); } for (DocumentDeletion deletion : indexModifications.getDocumentDeletions()) { ChronoIndexDocument document = deletion.getDocumentToDelete(); String branchName = document.getBranch(); SecondaryIndex index = document.getIndex(); if (!index.getBranch().equals(branchName)) { continue; } if (!index.getValidPeriod().contains(document.getValidFromTimestamp())) { continue; } // remove from index-name-to-documents map this.indexToDocuments.remove(index, document); // remove from general documents map Map<String, SetMultimap<String, ChronoIndexDocument>> keyspaceToKey = this.documents .get(index); if (keyspaceToKey == null) { continue; } SetMultimap<String, ChronoIndexDocument> keysToDocuments = keyspaceToKey.get(document.getKeyspace()); if (keysToDocuments == null) { continue; } Set<ChronoIndexDocument> documents = keysToDocuments.get(document.getKey()); if (documents == null) { continue; } documents.remove(document); } } @Override protected Set<ChronoIndexDocument> getDocumentsTouchedAtOrAfterTimestamp(final long timestamp, final Set<SecondaryIndex> indices) { checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); Set<ChronoIndexDocument> resultSet = Sets.newHashSet(); if (indices != null && indices.isEmpty()) { // no indices are requested, so the result set is empty by definition. return resultSet; } for (ChronoIndexDocument document : this.indexToDocuments.values()) { if (indices != null && indices.contains(document.getIndex()) == false) { // the index of the document is not in the set of requested indices -> ignore the document continue; } if (document.getValidFromTimestamp() >= timestamp) { // the document was added at or after the timestamp in question resultSet.add(document); } else if (document.getValidToTimestamp() < Long.MAX_VALUE && document.getValidToTimestamp() >= timestamp) { // the document was modified at or after the timestamp in question resultSet.add(document); } } return resultSet; } // ================================================================================================================= // INDEX QUERYING // ================================================================================================================= @Override public Map<SecondaryIndex, SetMultimap<Object, ChronoIndexDocument>> getMatchingBranchLocalDocuments( final ChronoIdentifier chronoIdentifier) { checkNotNull(chronoIdentifier, "Precondition violation - argument 'chronoIdentifier' must not be NULL!"); Map<SecondaryIndex, SetMultimap<Object, ChronoIndexDocument>> indexToIndexedValueToDocument = Maps.newHashMap(); for (Entry<SecondaryIndex, Map<String, SetMultimap<String, ChronoIndexDocument>>> entry : this.documents.entrySet()) { SecondaryIndex index = entry.getKey(); if (!index.getValidPeriod().contains(chronoIdentifier.getTimestamp())) { continue; } Map<String, SetMultimap<String, ChronoIndexDocument>> keyspaceToKey = entry.getValue(); if (keyspaceToKey == null) { continue; } SetMultimap<String, ChronoIndexDocument> keyToDocument = keyspaceToKey.get(chronoIdentifier.getKeyspace()); if (keyToDocument == null) { continue; } Set<ChronoIndexDocument> documents = keyToDocument.get(chronoIdentifier.getKey()); if (documents == null) { continue; } for (ChronoIndexDocument document : documents) { Object indexedValue = document.getIndexedValue(); SetMultimap<Object, ChronoIndexDocument> indexedValueToDocuments = indexToIndexedValueToDocument.get(index); if (indexedValueToDocuments == null) { indexedValueToDocuments = HashMultimap.create(); indexToIndexedValueToDocument.put(index, indexedValueToDocuments); } indexedValueToDocuments.put(indexedValue, document); } } return indexToIndexedValueToDocument; } @Override @SuppressWarnings({"unchecked", "rawtypes"}) public IndexScanCursor<?> createCursorOnIndex( final Branch branch, final long timestamp, final SecondaryIndex index, final String keyspace, final String indexName, final Order order, final TextCompare textCompare, final Set<String> keys ) { checkArgument(index.getBranch().equals(branch.getName()), "Precondition violation - argument 'index' refers to a different branch than the given argument 'branch'!" ); // TODO: this is GOD AWFUL. We really need to redo the inmemory backend... Set<ChronoIndexDocument> documents = this.indexToDocuments.get(index); List<IndexEntry> indexContents = Multimaps.index( documents, doc -> new IndexKey((Comparable<?>) doc.getIndexedValue(), doc.getKey()) ).asMap().entrySet().stream().map(entry -> { IndexKey key = entry.getKey(); List<Period> validPeriods = entry.getValue().stream() .map(ChronoIndexDocument::getValidPeriod) .sorted() .collect(Collectors.toList()); return new IndexEntry(key, validPeriods); }).sorted(IndexEntry.createComparator(textCompare)).collect(Collectors.toList()); if(order == Order.DESCENDING){ indexContents = Lists.reverse(indexContents); } RawIndexCursor<?> rawCursor = new RawInMemoryIndexCursor(indexContents.iterator(), order); if (branch.getName().equals(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER)) { // on the master branch, we can use the simple scans as we don't have // to watch out for deltas. IndexScanCursor<?> cursor = new BasicIndexScanCursor(rawCursor, timestamp); if (keys != null) { cursor = cursor.filter(k -> keys.contains(k.getSecond())); } return cursor; } // create the cursor on the parent Branch parentBranch = branch.getOrigin(); long parentTimestamp = Math.min(timestamp, branch.getBranchingTimestamp()); AbstractIndexManager indexManager = (AbstractIndexManager) this.owningDB.getIndexManager(); IndexScanCursor<?> parentCursor = indexManager.createCursor(parentTimestamp, parentBranch, keyspace, indexName, order, textCompare, keys); IndexScanCursor<?> scanCursor = new DeltaResolvingScanCursor(parentCursor, timestamp, rawCursor); if (keys != null) { scanCursor = scanCursor.filter(k -> keys.contains(k.getSecond())); } return scanCursor; } // ================================================================================================================= // INTERNAL HELPER METHODS // ================================================================================================================= @Override protected Set<ChronoIndexDocument> getMatchingBranchLocalDocuments( final long timestamp, final String branchName, final String keyspace, final SearchSpecification<?, ?> searchSpec ) { checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must be >= 0 (value: " + timestamp + ")!"); checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!"); checkNotNull(searchSpec, "Precondition violation - argument 'searchSpec' must not be NULL!"); SecondaryIndex index = searchSpec.getIndex(); Map<String, SetMultimap<String, ChronoIndexDocument>> keyspaceToKeyToDoc = this.documents.get(index); if (keyspaceToKeyToDoc == null || keyspaceToKeyToDoc.isEmpty()) { return Collections.emptySet(); } SetMultimap<String, ChronoIndexDocument> keyToDoc = keyspaceToKeyToDoc.get(keyspace); if (keyToDoc == null || keyToDoc.isEmpty()) { return Collections.emptySet(); } Predicate<? super ChronoIndexDocument> filter = this.createMatchFilter(timestamp, searchSpec.toFilterPredicate()); return Collections.unmodifiableSet(keyToDoc.values().stream().filter(filter).collect(Collectors.toSet())); } @Override protected Set<ChronoIndexDocument> getTerminatedBranchLocalDocuments(final long timestamp, final String branchName, final String keyspace, final SearchSpecification<?, ?> searchSpec) { checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must be >= 0 (value: " + timestamp + ")!"); checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!"); checkNotNull(searchSpec, "Precondition violation - argument 'searchSpec' must not be NULL!"); SecondaryIndex index = searchSpec.getIndex(); Map<String, SetMultimap<String, ChronoIndexDocument>> keyspaceToKeyToDoc = this.documents.get(index); if (keyspaceToKeyToDoc == null || keyspaceToKeyToDoc.isEmpty()) { return Collections.emptySet(); } SetMultimap<String, ChronoIndexDocument> keyToDoc = keyspaceToKeyToDoc.get(keyspace); if (keyToDoc == null || keyToDoc.isEmpty()) { return Collections.emptySet(); } Predicate<? super ChronoIndexDocument> filter = this.createDeletionFilter(timestamp, searchSpec.toFilterPredicate()); return Collections.unmodifiableSet(keyToDoc.values().stream().filter(filter).collect(Collectors.toSet())); } private Predicate<? super ChronoIndexDocument> createMatchFilter(final long timestamp, final Predicate<Object> filterPredicate) { return (doc) -> { Object indexedValue = doc.getIndexedValue(); boolean timeRangeOk = doc.getValidFromTimestamp() <= timestamp && timestamp < doc.getValidToTimestamp(); if (timeRangeOk == false) { return false; } return filterPredicate.test(indexedValue); }; } private Predicate<? super ChronoIndexDocument> createDeletionFilter(final long timestamp, final Predicate<Object> filterPredicate) { return (doc) -> { boolean timeRangeOk = doc.getValidToTimestamp() <= timestamp; if (timeRangeOk == false) { return false; } return filterPredicate.test(doc.getIndexedValue()); }; } protected void terminateDocumentValidity(final ChronoIndexDocument indexDocument, final long timestamp) { checkNotNull(indexDocument, "Precondition violation - argument 'indexDocument' must not be NULL!"); checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); // for in-memory, we only need to set the termination timestamp indexDocument.setValidToTimestamp(timestamp); } protected void addDocument(final ChronoIndexDocument document) { SecondaryIndex index = document.getIndex(); this.indexToDocuments.put(index, document); String branch = document.getBranch(); String keyspace = document.getKeyspace(); String key = document.getKey(); Map<String, SetMultimap<String, ChronoIndexDocument>> keyspaceToDocuments = this.documents.get(index); if (keyspaceToDocuments == null) { keyspaceToDocuments = Maps.newHashMap(); this.documents.put(index, keyspaceToDocuments); } SetMultimap<String, ChronoIndexDocument> keyToDocuments = keyspaceToDocuments.get(keyspace); if (keyToDocuments == null) { keyToDocuments = HashMultimap.create(); keyspaceToDocuments.put(keyspace, keyToDocuments); } keyToDocuments.put(key, document); } }
17,796
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoDBInMemoryBuilderImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/inmemory/builder/ChronoDBInMemoryBuilderImpl.java
package org.chronos.chronodb.inmemory.builder; import org.chronos.chronodb.inmemory.InMemoryChronoDB; import org.chronos.chronodb.internal.api.ChronoDBConfiguration; import org.chronos.chronodb.internal.impl.builder.database.AbstractChronoDBFinalizableBuilder; public class ChronoDBInMemoryBuilderImpl extends AbstractChronoDBFinalizableBuilder<ChronoDBInMemoryBuilder> implements ChronoDBInMemoryBuilder { public ChronoDBInMemoryBuilderImpl() { this.withProperty(ChronoDBConfiguration.STORAGE_BACKEND, InMemoryChronoDB.BACKEND_NAME); } }
549
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoDBInMemoryBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/inmemory/builder/ChronoDBInMemoryBuilder.java
package org.chronos.chronodb.inmemory.builder; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.builder.database.ChronoDBBackendBuilder; import org.chronos.chronodb.api.builder.database.ChronoDBFinalizableBuilder; /** * A builder for in-memory instances of {@link ChronoDB}. * * <p> * In-memory instance have no persistent representation; all changes to them are gone when the JVM terminates and/or the * garbage collector removes the ChronoDB instance from memory. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public interface ChronoDBInMemoryBuilder extends ChronoDBFinalizableBuilder<ChronoDBInMemoryBuilder>, ChronoDBBackendBuilder { }
708
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
InMemoryChronoDBTestSuitePlugin.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/inmemory/provider/InMemoryChronoDBTestSuitePlugin.java
package org.chronos.chronodb.inmemory.provider; import org.apache.commons.configuration2.BaseConfiguration; import org.apache.commons.configuration2.Configuration; import org.chronos.chronodb.api.builder.database.spi.TestSuitePlugin; import org.chronos.chronodb.inmemory.InMemoryChronoDB; import org.chronos.chronodb.internal.api.ChronoDBConfiguration; import java.io.File; import java.lang.reflect.Method; public class InMemoryChronoDBTestSuitePlugin implements TestSuitePlugin { @Override public Configuration createBasicTestConfiguration(final Method testMethod, final File testDirectory) { Configuration configuration = new BaseConfiguration(); configuration.setProperty(ChronoDBConfiguration.STORAGE_BACKEND, InMemoryChronoDB.BACKEND_NAME); return configuration; } @Override public void onBeforeTest(final Class<?> testClass, final Method testMethod, final File testDirectory) { // nothing to do } @Override public void onAfterTest(final Class<?> testClass, final Method testMethod, final File testDirectory) { // nothing to do } }
1,119
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
InMemoryChronoDBBackendProvider.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/inmemory/provider/InMemoryChronoDBBackendProvider.java
package org.chronos.chronodb.inmemory.provider; import com.google.common.collect.Sets; import org.apache.commons.configuration2.Configuration; import org.chronos.chronodb.api.builder.database.ChronoDBBackendBuilder; import org.chronos.chronodb.api.builder.database.spi.ChronoDBBackendProvider; import org.chronos.chronodb.api.builder.database.spi.TestSuitePlugin; import org.chronos.chronodb.inmemory.InMemoryChronoDB; import org.chronos.chronodb.inmemory.InMemoryChronoDBConfiguration; import org.chronos.chronodb.inmemory.builder.ChronoDBInMemoryBuilderImpl; import org.chronos.chronodb.internal.api.ChronoDBInternal; import org.chronos.common.configuration.ChronosConfigurationUtil; import java.util.Collections; import java.util.Set; import static com.google.common.base.Preconditions.*; public class InMemoryChronoDBBackendProvider implements ChronoDBBackendProvider { private static final Set<String> SUPPORTED_BACKEND_NAMES = Collections.unmodifiableSet(Sets.newHashSet(InMemoryChronoDB.BACKEND_NAME, "memory", "in-memory")); private final TestSuitePlugin testSuitePlugin = new InMemoryChronoDBTestSuitePlugin(); @Override public boolean matchesBackendName(final String backendName) { checkNotNull(backendName, "Precondition violation - argument 'bak' must not be NULL!"); return SUPPORTED_BACKEND_NAMES.contains(backendName); } @Override public Class<InMemoryChronoDBConfiguration> getConfigurationClass() { return InMemoryChronoDBConfiguration.class; } @Override public ChronoDBInternal instantiateChronoDB(final Configuration configuration) { InMemoryChronoDBConfiguration config = ChronosConfigurationUtil.build(configuration, this.getConfigurationClass()); return new InMemoryChronoDB(config); } @Override public String getBackendName() { return InMemoryChronoDB.BACKEND_NAME; } @Override public TestSuitePlugin getTestSuitePlugin() { return this.testSuitePlugin; } @Override public ChronoDBBackendBuilder createBuilder() { return new ChronoDBInMemoryBuilderImpl(); } }
2,137
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronosCommonTestSuite.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/test/java/org/chronos/common/test/_suite/ChronosCommonTestSuite.java
package org.chronos.common.test._suite; import org.chronos.common.test.junit.ExcludeCategories; import org.chronos.common.test.junit.PackageSuite; import org.chronos.common.test.junit.SuitePackages; import org.chronos.common.test.junit.categories.PerformanceTest; import org.chronos.common.test.junit.categories.SlowTest; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.junit.runners.Suite; @Category(Suite.class) @RunWith(PackageSuite.class) @SuitePackages("org.chronos.common.test.cases") @ExcludeCategories({PerformanceTest.class, SlowTest.class}) public class ChronosCommonTestSuite { }
641
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
KryoManagerTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/test/java/org/chronos/common/test/cases/serialization/KryoManagerTest.java
package org.chronos.common.test.cases.serialization; import org.chronos.common.serialization.KryoManager; import org.junit.Test; import java.io.File; import java.io.IOException; import java.util.List; import static org.junit.Assert.*; public class KryoManagerTest { @Test public void canSerializeAndDeserialize() { Person johnDoe = new Person("John", "Doe"); byte[] bytes = KryoManager.serialize(johnDoe); assertNotNull(bytes); Person deserialized = KryoManager.deserialize(bytes); assertEquals(johnDoe, deserialized); } @Test public void canDuplicate() { Person johnDoe = new Person("John", "Doe"); Person clone = KryoManager.deepCopy(johnDoe); assertEquals(johnDoe, clone); } @Test public void canSerializeAndDeserializeWithFiles() { try { File testFile = File.createTempFile("tempFile", "binary"); testFile.deleteOnExit(); Person johnDoe = new Person("John", "Doe"); KryoManager.serializeObjectsToFile(testFile, johnDoe); Person deserialized = KryoManager.deserializeObjectFromFile(testFile); assertNotNull(deserialized); assertEquals(johnDoe, deserialized); } catch (IOException ioe) { fail(ioe.toString()); } } @Test public void canSerializeAndDeserializeMultipleObjectsWithFiles() { try { File testFile = File.createTempFile("tempFile", "binary"); testFile.deleteOnExit(); Person p1 = new Person("John", "Doe"); Person p2 = new Person("Jane", "Doe"); KryoManager.serializeObjectsToFile(testFile, p1, p2); List<Object> deserializedObjects = KryoManager.deserializeObjectsFromFile(testFile); assertNotNull(deserializedObjects); assertEquals(2, deserializedObjects.size()); assertEquals(p1, deserializedObjects.get(0)); assertEquals(p2, deserializedObjects.get(1)); } catch (IOException ioe) { fail(ioe.toString()); } } // ===================================================================================================================== // INNER CLASSES // ===================================================================================================================== @SuppressWarnings("unused") private static class Person { private String firstName; private String lastName; protected Person() { // default constructor for serialization this(null, null); } public Person(final String firstName, final String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return this.firstName; } public void setFirstName(final String firstName) { this.firstName = firstName; } public String getLastName() { return this.lastName; } public void setLastName(final String lastName) { this.lastName = lastName; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.firstName == null ? 0 : this.firstName.hashCode()); result = prime * result + (this.lastName == null ? 0 : this.lastName.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; } Person other = (Person) obj; if (this.firstName == null) { if (other.firstName != null) { return false; } } else if (!this.firstName.equals(other.firstName)) { return false; } if (this.lastName == null) { if (other.lastName != null) { return false; } } else if (!this.lastName.equals(other.lastName)) { return false; } return true; } } }
4,431
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
MyConfiguration.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/test/java/org/chronos/common/test/cases/configuration/MyConfiguration.java
package org.chronos.common.test.cases.configuration; import com.google.common.collect.Sets; import org.chronos.common.configuration.AbstractConfiguration; import org.chronos.common.configuration.Comparison; import org.chronos.common.configuration.ParameterValueConverter; import org.chronos.common.configuration.annotation.EnumFactoryMethod; import org.chronos.common.configuration.annotation.IgnoredIf; import org.chronos.common.configuration.annotation.Namespace; import org.chronos.common.configuration.annotation.Parameter; import org.chronos.common.configuration.annotation.RequiredIf; import org.chronos.common.configuration.annotation.ValueAlias; import org.chronos.common.configuration.annotation.ValueConverter; import java.time.DayOfWeek; import java.util.Collections; import java.util.Set; import static com.google.common.base.Preconditions.*; @Namespace("org.chronos.common.test") public class MyConfiguration extends AbstractConfiguration { @Parameter private String name; @Parameter(key = "integer", optional = false) private int intValue = 42; @ValueAlias(alias = "mon", mapTo = "MONDAY") @ValueAlias(alias = "tue", mapTo = "TUESDAY") @ValueAlias(alias = "wed", mapTo = "WEDNESDAY") @ValueAlias(alias = "thu", mapTo = "THURSDAY") @ValueAlias(alias = "fri", mapTo = "FRIDAY") @ValueAlias(alias = "sat", mapTo = "SATURDAY") @ValueAlias(alias = "sun", mapTo = "SUNDAY") @Parameter(key = "org.chronos.common.test.day", optional = true) private DayOfWeek dayOfWeek; @Parameter @IgnoredIf(field = "dayOfWeek", comparison = Comparison.IS_SET_TO, compareValue = "SATURDAY") @IgnoredIf(field = "dayOfWeek", comparison = Comparison.IS_SET_TO, compareValue = "SUNDAY") private Double motivation; @Parameter() @RequiredIf(field = "dayOfWeek", comparison = Comparison.IS_SET_TO, compareValue = "MONDAY") private Boolean hangover; @Parameter(optional = true) @ValueConverter(CoordinateParser.class) private Coordinate coordinate; @Parameter(optional = true) @EnumFactoryMethod("fromString") private MyEnum myEnum; public MyConfiguration() { } public String getName() { return this.name; } public int getIntValue() { return this.intValue; } public DayOfWeek getDayOfWeek() { return this.dayOfWeek; } public double getMotivation() { return this.motivation; } public boolean isHangover() { return this.hangover; } public Coordinate getCoordinate() { return this.coordinate; } public MyEnum getMyEnum() { return this.myEnum; } public static class Coordinate { private String x; private String y; public Coordinate(final String x, final String y) { this.x = x; this.y = y; } public String getX() { return this.x; } public String getY() { return this.y; } } public static class CoordinateParser implements ParameterValueConverter { @Override public Object convert(final Object rawParameter) { String string = String.valueOf(rawParameter); char separator = ';'; int separatorIndex = string.indexOf(separator); String x = string.substring(1, separatorIndex); String y = string.substring(separatorIndex + 1, string.length() - 1); return new Coordinate(x, y); } } public static enum MyEnum { ONE("one", "1"), TWO("2", "two"), THREE("3", "three"); private final String primaryName; private final Set<String> aliases; private final Set<String> allNames; private MyEnum(final String primaryName, final String... aliases) { checkNotNull(primaryName, "Precondition violation - argument 'primaryName' must not be NULL!"); this.primaryName = primaryName; Set<String> myAliases = Sets.newHashSet(); if (aliases != null && aliases.length > 0) { for (String alias : aliases) { myAliases.add(alias); } } this.aliases = Collections.unmodifiableSet(myAliases); Set<String> myNames = Sets.newHashSet(); myNames.add(primaryName); myNames.addAll(this.aliases); this.allNames = Collections.unmodifiableSet(myNames); } @Override public String toString() { return this.primaryName; } public static MyEnum fromString(final String stringValue) { checkNotNull(stringValue, "Precondition violation - argument 'stringValue' must not be NULL!"); String token = stringValue.toLowerCase().trim(); if (token.isEmpty()) { throw new IllegalArgumentException("Cannot parse DuplicateVersionEliminationMode from empty string!"); } for (MyEnum literal : MyEnum.values()) { for (String name : literal.allNames) { if (name.equalsIgnoreCase(token)) { return literal; } } } throw new IllegalArgumentException("Unknown MyEnum: '" + token + "'!"); } } }
5,366
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
BooleanDependentConfiguration.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/test/java/org/chronos/common/test/cases/configuration/BooleanDependentConfiguration.java
package org.chronos.common.test.cases.configuration; import org.chronos.common.configuration.AbstractConfiguration; import org.chronos.common.configuration.Comparison; import org.chronos.common.configuration.annotation.Namespace; import org.chronos.common.configuration.annotation.Parameter; import org.chronos.common.configuration.annotation.RequiredIf; @Namespace("org.chronos.common.test") public class BooleanDependentConfiguration extends AbstractConfiguration { @Parameter private Boolean bool; @Parameter @RequiredIf(field = "bool", comparison = Comparison.IS_SET_TO, compareValue = "true") private String string; public Boolean getBool() { return this.bool; } public String getString() { return this.string; } }
779
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronosConfigurationUtilTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/test/java/org/chronos/common/test/cases/configuration/ChronosConfigurationUtilTest.java
package org.chronos.common.test.cases.configuration; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; import com.google.common.collect.Lists; import com.google.common.io.Resources; import org.apache.commons.configuration2.Configuration; import org.apache.commons.configuration2.PropertiesConfiguration; import org.apache.commons.configuration2.ex.ConfigurationException; import org.chronos.common.configuration.ChronosConfigurationUtil; import org.chronos.common.exceptions.ChronosConfigurationException; import org.chronos.common.test.cases.configuration.MyConfiguration.MyEnum; import org.jetbrains.annotations.NotNull; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.time.DayOfWeek; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import static org.junit.Assert.*; public class ChronosConfigurationUtilTest { private TestAppender logSpy; @Before public void installTestAppender() { this.logSpy = new TestAppender(); LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); this.logSpy.setContext(lc); Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); root.addAppender(this.logSpy); } @After public void uninstallTestAppender() { Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); root.detachAppender(this.logSpy); this.logSpy.clearEvents(); this.logSpy = null; } @Test public void correctConfiguration1Works() throws Exception { PropertiesConfiguration apacheConfig = this.createPropertiesConfiguration("myconfiguration_correct1.properties"); MyConfiguration config = ChronosConfigurationUtil.build(apacheConfig, MyConfiguration.class); assertEquals("Martin", config.getName()); assertEquals(47, config.getIntValue()); assertEquals(DayOfWeek.SUNDAY, config.getDayOfWeek()); } @Test public void correctConfiguration2Works() throws Exception { Configuration apacheConfig = this.createPropertiesConfiguration("myconfiguration_correct2.properties"); MyConfiguration config = ChronosConfigurationUtil.build(apacheConfig, MyConfiguration.class); assertEquals("Martin", config.getName()); assertEquals(47, config.getIntValue()); assertEquals(DayOfWeek.MONDAY, config.getDayOfWeek()); assertEquals(true, config.isHangover()); assertEquals(100.0, config.getMotivation(), 0.1d); } @Test public void valueAliasingWorks() throws Exception { Configuration apacheConfig = this.createPropertiesConfiguration("myconfiguration_aliasing.properties"); MyConfiguration config = ChronosConfigurationUtil.build(apacheConfig, MyConfiguration.class); assertEquals("Martin", config.getName()); assertEquals(47, config.getIntValue()); assertEquals(DayOfWeek.MONDAY, config.getDayOfWeek()); assertEquals(true, config.isHangover()); assertEquals(100.0, config.getMotivation(), 0.1d); } @Test public void customValueParsingWorks() throws Exception { Configuration apacheConfig = this.createPropertiesConfiguration("myconfiguration_valueparser.properties"); MyConfiguration config = ChronosConfigurationUtil.build(apacheConfig, MyConfiguration.class); assertEquals("Martin", config.getName()); assertEquals(47, config.getIntValue()); assertEquals(DayOfWeek.MONDAY, config.getDayOfWeek()); assertEquals(true, config.isHangover()); assertEquals(100.0, config.getMotivation(), 0.1d); assertEquals("123", config.getCoordinate().getX()); assertEquals("456", config.getCoordinate().getY()); } @Test public void configWithSuperfluousParametersWorks() throws Exception { Configuration apacheConfig = this.createPropertiesConfiguration("myconfiguration_superfluous1.properties"); MyConfiguration config = ChronosConfigurationUtil.build(apacheConfig, MyConfiguration.class); assertEquals("Martin", config.getName()); assertEquals(47, config.getIntValue()); assertEquals(DayOfWeek.MONDAY, config.getDayOfWeek()); assertEquals(true, config.isHangover()); assertEquals(100.0, config.getMotivation(), 0.1d); // assert that we have printed a warning assertEquals(1, this.logSpy.getWarnings().size()); } @Test(expected = ChronosConfigurationException.class) public void missingValuesAreDetectedProperly() throws Exception { Configuration apacheConfig = this.createPropertiesConfiguration("myconfiguration_error1.properties"); ChronosConfigurationUtil.build(apacheConfig, MyConfiguration.class); } @Test(expected = ChronosConfigurationException.class) public void wrongEnumValuesAreDetectedProperly() throws Exception{ Configuration apacheConfig = this.createPropertiesConfiguration("myconfiguration_error2.properties"); ChronosConfigurationUtil.build(apacheConfig, MyConfiguration.class); } @Test public void enumFactoryMethodAnnotationWorks() throws Exception{ Configuration apacheConfig = this.createPropertiesConfiguration("myconfiguration_enumFactoryMethod.properties"); MyConfiguration config = ChronosConfigurationUtil.build(apacheConfig, MyConfiguration.class); assertEquals(MyEnum.THREE, config.getMyEnum()); } @Test public void canDependOnAValueOfTypeBoolean_case1() throws Exception{ // case 1: boolean is true, and dependent value is present Configuration apacheConfig = this.createPropertiesConfiguration("booleanDependentConfiguration_correct.properties"); BooleanDependentConfiguration config = ChronosConfigurationUtil.build(apacheConfig, BooleanDependentConfiguration.class); assertEquals(true, config.getBool()); assertEquals("yes", config.getString()); } @Test public void canDependOnAValueOfTypeBoolean_case2() throws Exception{ // case 2: boolean is false Configuration apacheConfig = this.createPropertiesConfiguration("booleanDependentConfiguration_correct2.properties"); BooleanDependentConfiguration config = ChronosConfigurationUtil.build(apacheConfig, BooleanDependentConfiguration.class); assertEquals(false, config.getBool()); } @Test public void canDependOnAValueOfTypeBoolean_case3() throws Exception{ // case 3: boolean is true, but dependent value is missing try { Configuration apacheConfig = this.createPropertiesConfiguration("booleanDependentConfiguration_wrong.properties"); ChronosConfigurationUtil.build(apacheConfig, BooleanDependentConfiguration.class); fail(); } catch (ChronosConfigurationException expected) { // pass } } @NotNull private PropertiesConfiguration createPropertiesConfiguration(String fileName) throws IOException, ConfigurationException { PropertiesConfiguration apacheConfig = new PropertiesConfiguration(); try (InputStream inputStream = Resources.getResource(fileName).openStream()) { try (Reader reader = new InputStreamReader(inputStream)) { apacheConfig.read(reader); } } return apacheConfig; } private static class TestAppender extends AppenderBase<ILoggingEvent> { private List<ILoggingEvent> events = Lists.newArrayList(); @Override public String getName() { return "LogSpy"; } @Override public void doAppend(final ILoggingEvent eventObject) { this.events.add(eventObject); } public void clearEvents() { this.events.clear(); } public List<ILoggingEvent> getEvents() { return Collections.unmodifiableList(this.events); } public List<ILoggingEvent> getWarnings() { return this.getEvents().stream().filter(e -> e.getLevel().equals(Level.WARN)).collect(Collectors.toList()); } @SuppressWarnings("unused") public List<ILoggingEvent> getErrors() { return this.getEvents().stream().filter(e -> e.getLevel().equals(Level.ERROR)).collect(Collectors.toList()); } @Override protected void append(final ILoggingEvent eventObject) { // unused; see 'doAppend' } } }
8,838
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronosVersionTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/test/java/org/chronos/common/test/cases/version/ChronosVersionTest.java
package org.chronos.common.test.cases.version; import org.chronos.common.version.ChronosVersion; import org.chronos.common.version.VersionKind; import org.junit.Test; import static com.google.common.base.Preconditions.*; import static org.junit.Assert.*; public class ChronosVersionTest { @Test public void canGetCurrentVersion() { ChronosVersion currentVersion = ChronosVersion.getCurrentVersion(); checkNotNull(currentVersion, "Precondition violation - argument 'currentVersion' must not be NULL!"); } @Test public void canConvertToAndFromString() { ChronosVersion version1 = new ChronosVersion(1, 2, 3, VersionKind.RELEASE); ChronosVersion version2 = new ChronosVersion(0, 0, 0, VersionKind.SNAPSHOT); ChronosVersion version3 = new ChronosVersion(0, 1, 0, VersionKind.RELEASE); ChronosVersion version4 = new ChronosVersion(1, 0, 0, VersionKind.RELEASE); assertEquals(version1, ChronosVersion.parse(version1.toString())); assertEquals(version2, ChronosVersion.parse(version2.toString())); assertEquals(version3, ChronosVersion.parse(version3.toString())); assertEquals(version4, ChronosVersion.parse(version4.toString())); } @Test public void noTagIsInterpretedAsRelease() { ChronosVersion version = new ChronosVersion(0, 5, 5, VersionKind.RELEASE); assertEquals(version, ChronosVersion.parse("0.5.5")); } @Test public void readCompatibilityIsIndicatedCorrectly() { ChronosVersion v054snapshot = new ChronosVersion(0, 5, 4, VersionKind.SNAPSHOT); ChronosVersion v054release = new ChronosVersion(0, 5, 4, VersionKind.RELEASE); ChronosVersion v055snapshot = new ChronosVersion(0, 5, 5, VersionKind.SNAPSHOT); ChronosVersion v060snapshot = new ChronosVersion(0, 6, 0, VersionKind.SNAPSHOT); assertTrue(v054snapshot.isReadCompatibleWith(v054release)); assertTrue(v054snapshot.isReadCompatibleWith(v055snapshot)); assertTrue(v054release.isReadCompatibleWith(v054snapshot)); assertTrue(v055snapshot.isReadCompatibleWith(v054snapshot)); assertTrue(v060snapshot.isReadCompatibleWith(v054snapshot)); assertTrue(v060snapshot.isReadCompatibleWith(v054release)); assertTrue(v060snapshot.isReadCompatibleWith(v055snapshot)); assertFalse(v054snapshot.isReadCompatibleWith(v060snapshot)); assertFalse(v054release.isReadCompatibleWith(v060snapshot)); assertFalse(v055snapshot.isReadCompatibleWith(v060snapshot)); } }
2,571
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronosBuildConfiguration.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/buildinfo/ChronosBuildConfiguration.java
package org.chronos.common.buildinfo; public interface ChronosBuildConfiguration { // ===================================================================================================================== // STATIC KEY NAMES // ===================================================================================================================== public static final String NAMESPACE = "org.chronos"; public static final String NS_DOT = NAMESPACE + '.'; public static final String BUILD_VERSION = NS_DOT + "buildVersion"; // ================================================================================================================= // GENERAL CONFIGURATION // ================================================================================================================= public String getBuildVersion(); }
831
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronosBuildConfigurationImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/buildinfo/ChronosBuildConfigurationImpl.java
package org.chronos.common.buildinfo; import org.chronos.common.configuration.AbstractConfiguration; import org.chronos.common.configuration.annotation.Namespace; import org.chronos.common.configuration.annotation.Parameter; @Namespace(ChronosBuildConfiguration.NAMESPACE) public class ChronosBuildConfigurationImpl extends AbstractConfiguration implements ChronosBuildConfiguration { // ===================================================================================================================== // PROPERTIES // ===================================================================================================================== @Parameter(key = ChronosBuildConfiguration.BUILD_VERSION, optional = false) private String chronosVersion; // ===================================================================================================================== // GETTERS // ===================================================================================================================== @Override public String getBuildVersion() { return this.chronosVersion; } }
1,096
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronosBuildInfo.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/buildinfo/ChronosBuildInfo.java
package org.chronos.common.buildinfo; import java.io.File; import java.io.FileReader; import org.apache.commons.configuration2.Configuration; import org.apache.commons.configuration2.PropertiesConfiguration; import org.chronos.common.configuration.ChronosConfigurationUtil; import org.chronos.common.util.ClasspathUtils; public class ChronosBuildInfo { // ===================================================================================================================== // CONSTANTS // ===================================================================================================================== private static final String BUILD_INFO_FILE_NAME = "buildInfo.properties"; private static ChronosBuildConfiguration CONFIGURATION; public static synchronized ChronosBuildConfiguration getConfiguration() { if (CONFIGURATION == null) { try { File buildInfoFile = ClasspathUtils.getResourceAsFile(BUILD_INFO_FILE_NAME); if (buildInfoFile == null || buildInfoFile.exists() == false || buildInfoFile.isFile() == false) { throw new IllegalStateException("Unable to retrieve file '" + BUILD_INFO_FILE_NAME + "'!"); } PropertiesConfiguration apacheConfig = new PropertiesConfiguration(); try(FileReader reader = new FileReader(buildInfoFile)){ apacheConfig.read(reader); } CONFIGURATION = ChronosConfigurationUtil.build(apacheConfig, ChronosBuildConfigurationImpl.class); } catch (Exception e) { throw new IllegalStateException( "An exception occurred when reading the Chronos Build Configuration. See root cause for details.", e); } } return CONFIGURATION; } }
1,645
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronosLogMarker.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/logging/ChronosLogMarker.java
package org.chronos.common.logging; import org.slf4j.Marker; import org.slf4j.MarkerFactory; public class ChronosLogMarker { public static final Marker CHRONOS_LOG_MARKER__PERFORMANCE = MarkerFactory.getMarker("org.chronos.logmarker.performance"); public static final Marker CHRONOS_LOG_MARKER__GRAPH_MODIFICATIONS = MarkerFactory.getMarker("org.chronos.logmarker.graphmodifications"); }
401
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronosConfigurationException.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/exceptions/ChronosConfigurationException.java
package org.chronos.common.exceptions; public class ChronosConfigurationException extends ChronosException { protected ChronosConfigurationException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public ChronosConfigurationException() { super(); } public ChronosConfigurationException(final String message, final Throwable cause) { super(message, cause); } public ChronosConfigurationException(final String message) { super(message); } public ChronosConfigurationException(final Throwable cause) { super(cause); } }
677
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
NotInstantiableException.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/exceptions/NotInstantiableException.java
package org.chronos.common.exceptions; public class NotInstantiableException extends RuntimeException { public NotInstantiableException() { super(); } public NotInstantiableException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public NotInstantiableException(final String message, final Throwable cause) { super(message, cause); } public NotInstantiableException(final String message) { super(message); } public NotInstantiableException(final Throwable cause) { super(cause); } }
644
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
UnknownEnumLiteralException.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/exceptions/UnknownEnumLiteralException.java
package org.chronos.common.exceptions; public class UnknownEnumLiteralException extends RuntimeException { private final String message; // ================================================================================================================= // CONSTRUCTORS // ================================================================================================================= public UnknownEnumLiteralException(final Object enumLiteral) { if (enumLiteral == null) { this.message = "Encountered enum literal NULL!"; } else { String className = enumLiteral.getClass().getName(); this.message = "Encountered unknown literal of enum class '" + className + "': '" + enumLiteral + "'!"; } } // ================================================================================================================= // GETTERS // ================================================================================================================= @Override public String getMessage() { return this.message; } }
1,040
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronosIOException.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/exceptions/ChronosIOException.java
package org.chronos.common.exceptions; public class ChronosIOException extends ChronosException { public ChronosIOException() { super(); } protected ChronosIOException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public ChronosIOException(final String message, final Throwable cause) { super(message, cause); } public ChronosIOException(final String message) { super(message); } public ChronosIOException(final Throwable cause) { super(cause); } }
608
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronosException.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/exceptions/ChronosException.java
package org.chronos.common.exceptions; public class ChronosException extends RuntimeException { public ChronosException() { super(); } public ChronosException(final String message) { super(message); } public ChronosException(final Throwable cause) { super(cause); } public ChronosException(final String message, final Throwable cause) { super(message, cause); } public ChronosException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
596
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
KryoManager.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/serialization/KryoManager.java
package org.chronos.common.serialization; import static com.google.common.base.Preconditions.*; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.List; import org.chronos.common.exceptions.ChronosIOException; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.google.common.collect.Lists; public class KryoManager { // ===================================================================================================================== // CONSTANTS // ===================================================================================================================== private static final int KRYO_REUSE_WRITTEN_BYTES_THRESHOLD_BYTES = 1024 * 1024 * 2; // 2MB private static final int KRYO_REUSE_USAGE_COUNT_THRESHOLD = 2000; // ===================================================================================================================== // STATIC FIELDS // ===================================================================================================================== private static final ThreadLocal<KryoWrapper> THREAD_LOCAL_KRYO = new ThreadLocal<KryoWrapper>(); // ===================================================================================================================== // PUBLIC API // ===================================================================================================================== public static void destroyKryo() { THREAD_LOCAL_KRYO.remove(); } public static byte[] serialize(final Object object) { return getKryo().serialize(object); } public static <T> T deserialize(final byte[] serialForm) { return getKryo().deserialize(serialForm); } public static <T> T deepCopy(final T element) { return getKryo().deepCopy(element); } public static void serializeObjectsToFile(final File file, final Object... objects) { checkNotNull(objects, "Precondition violation - argument 'objects' must not be NULL!"); checkNotNull(file, "Precondition violation - argument 'file' must not be NULL!"); checkArgument(file.exists(), "Precondition violation - argument 'file' must refer to an existing file!"); checkArgument(file.isFile(), "Precondition violation - argument 'file' must refer to a file (not a directory)!"); checkArgument(file.canWrite(), "Precondition violation - argument 'file' must be writable!"); try { getKryo().serializeToFile(file, objects); } catch (IOException e) { throw new ChronosIOException("Failed to serialize object to file!", e); } } public static <T> T deserializeObjectFromFile(final File file) { checkNotNull(file, "Precondition violation - argument 'file' must not be NULL!"); checkArgument(file.exists(), "Precondition violation - argument 'file' must refer to an existing file!"); checkArgument(file.isFile(), "Precondition violation - argument 'file' must refer to a file (not a directory)!"); checkArgument(file.canRead(), "Precondition violation - argument 'file' must be readable!"); try { return getKryo().deserializeObjectFromFile(file); } catch (IOException e) { throw new ChronosIOException("Failed to deserialize object from file!", e); } } public static List<Object> deserializeObjectsFromFile(final File file) { checkArgument(file.exists(), "Precondition violation - argument 'file' must refer to an existing file!"); checkArgument(file.isFile(), "Precondition violation - argument 'file' must refer to a file (not a directory)!"); checkArgument(file.canRead(), "Precondition violation - argument 'file' must be readable!"); try { return getKryo().deserializeObjectsFromFile(file); } catch (IOException e) { throw new ChronosIOException("Failed to deserialize object(s) from file!", e); } } // ===================================================================================================================== // INTERNAL HELPER METHODS // ===================================================================================================================== private static KryoWrapper getKryo() { KryoWrapper kryoWrapper = THREAD_LOCAL_KRYO.get(); if (kryoWrapper == null) { return produceKryoWrapper(); } return kryoWrapper; } private static KryoWrapper produceKryoWrapper() { KryoWrapper wrapper = new KryoWrapper(); THREAD_LOCAL_KRYO.set(wrapper); return wrapper; } // ===================================================================================================================== // INNER CLASSES // ===================================================================================================================== private static class KryoWrapper { private WeakReference<Kryo> kryoReference = null; private int usageCount = 0; private long serializedBytes = 0; // ================================================================================================================= // PUBLIC API // ================================================================================================================= public byte[] serialize(final Object object) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Output output = new Output(baos); this.getKryo().writeClassAndObject(output, object); output.flush(); byte[] result = baos.toByteArray(); output.close(); this.serializedBytes += result.length; this.usageCount++; this.destroyKryoIfNecessary(); return result; } public void serializeToFile(final File file, final Object... objects) throws IOException { try (Output out = new Output(new FileOutputStream(file))) { for (Object object : objects) { this.getKryo().writeClassAndObject(out, object); } out.flush(); this.serializedBytes += file.length(); this.usageCount++; this.destroyKryoIfNecessary(); } } @SuppressWarnings("unchecked") public <T> T deserialize(final byte[] serialForm) { ByteArrayInputStream bais = new ByteArrayInputStream(serialForm); Input input = new Input(bais); Object object = this.getKryo().readClassAndObject(input); input.close(); this.usageCount++; this.destroyKryoIfNecessary(); return (T) object; } @SuppressWarnings("unchecked") public <T> T deserializeObjectFromFile(final File file) throws IOException { try (Input input = new Input(new FileInputStream(file))) { Object object = this.getKryo().readClassAndObject(input); this.usageCount++; this.destroyKryoIfNecessary(); return (T) object; } } public List<Object> deserializeObjectsFromFile(final File file) throws IOException { try (Input input = new Input(new FileInputStream(file))) { List<Object> resultList = Lists.newArrayList(); Kryo kryo = this.getKryo(); while (input.canReadInt()) { Object element = kryo.readClassAndObject(input); resultList.add(element); } this.usageCount++; this.destroyKryoIfNecessary(); return resultList; } } public <T> T deepCopy(final T element) { Kryo kryo = this.getKryo(); T copy = kryo.copy(element); // we have no idea how big the copied object is; // destroy our kryo instance as a precautionary measure this.destroyKryo(); return copy; } // ================================================================================================================= // INTERNAL API // ================================================================================================================= private Kryo produceKryo() { Kryo kryo = new Kryo(); this.kryoReference = new WeakReference<Kryo>(kryo); return kryo; } private Kryo getKryo() { if (this.kryoReference == null) { return this.produceKryo(); } Kryo kryo = this.kryoReference.get(); if (kryo == null) { return this.produceKryo(); } return kryo; } private void destroyKryo() { this.kryoReference = null; this.usageCount = 0; this.serializedBytes = 0; } private void destroyKryoIfNecessary() { if (this.serializedBytes >= KRYO_REUSE_WRITTEN_BYTES_THRESHOLD_BYTES) { this.destroyKryo(); } if (this.usageCount >= KRYO_REUSE_USAGE_COUNT_THRESHOLD) { this.destroyKryo(); } } } }
8,410
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
PersistentClass.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/annotation/PersistentClass.java
package org.chronos.common.annotation; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * This annotation indicates that the annotated class is persisted on disk. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API */ @Documented @Retention(RetentionPolicy.SOURCE) public @interface PersistentClass { public String value() default ""; }
444
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ParameterMetadata.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/configuration/ParameterMetadata.java
package org.chronos.common.configuration; import static com.google.common.base.Preconditions.*; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Collections; import java.util.Map; import java.util.Set; import org.chronos.common.configuration.annotation.EnumFactoryMethod; import org.chronos.common.configuration.annotation.IgnoredIf; import org.chronos.common.configuration.annotation.Namespace; import org.chronos.common.configuration.annotation.Parameter; import org.chronos.common.configuration.annotation.RequiredIf; import org.chronos.common.configuration.annotation.ValueAlias; import org.chronos.common.configuration.annotation.ValueConverter; import org.chronos.common.util.ReflectionUtils; import com.google.common.collect.Maps; import com.google.common.collect.Sets; public class ParameterMetadata { private final Field field; public ParameterMetadata(final Field parameterField) { checkNotNull(parameterField, "Precondition violation - argument 'parameterField' must not be NULL!"); Parameter parameter = parameterField.getAnnotation(Parameter.class); checkNotNull(parameter, "Precondition violation - argument 'parameterField' must have an @Parameter annotation!"); this.field = parameterField; } @SuppressWarnings("unchecked") public Class<? extends AbstractConfiguration> getConfigurationClass() { return (Class<? extends AbstractConfiguration>) this.field.getDeclaringClass(); } public Parameter getParameterAnnotation() { return this.field.getAnnotation(Parameter.class); } public Class<?> getType() { return this.field.getType(); } public boolean isOptional() { return this.getParameterAnnotation().optional(); } public String getNamespace() { Class<?> configClass = this.getConfigurationClass(); Namespace namespace = ReflectionUtils.getClassAnnotationRecursively(configClass, Namespace.class); if (namespace == null) { return null; } String value = namespace.value(); if (value == null || value.trim().isEmpty()) { return value; } return value.trim(); } public String getKey() { String namespace = this.getNamespace(); String key = this.getParameterAnnotation().key().trim(); if (key == null || key.isEmpty()) { key = this.field.getName(); } if (namespace == null) { return key; } if (key.startsWith(namespace + '.') && key.length() > namespace.length() + 1) { return key; } return namespace + '.' + key; } public boolean isConditionallyRequired() { RequiredIf[] requiredIfs = this.field.getAnnotationsByType(RequiredIf.class); if (requiredIfs != null && requiredIfs.length > 0) { return true; } else { return false; } } public boolean isConditionallyIgnored() { IgnoredIf[] ignoredIfs = this.field.getAnnotationsByType(IgnoredIf.class); if (ignoredIfs != null && ignoredIfs.length > 0) { return true; } else { return false; } } public Object getValue(final AbstractConfiguration config) { checkNotNull(config, "Precondition violation - argument 'config' must not be NULL!"); try { this.field.setAccessible(true); return this.field.get(config); } catch (IllegalArgumentException | IllegalAccessException e) { throw new IllegalArgumentException("Configuration class '" + config.getClass().getName() + "' does not support field '" + this.field.getName() + "'!", e); } } public void setValue(final AbstractConfiguration chronoConfig, final Object parameterValue) { checkNotNull(chronoConfig, "Precondition violation - argument 'chronoConfig' must not be NULL!"); checkNotNull(parameterValue, "Precondition violation - argument 'parameterValue' must not be NULL!"); try { this.field.setAccessible(true); this.field.set(chronoConfig, parameterValue); } catch (IllegalArgumentException | IllegalAccessException e) { throw new IllegalArgumentException( "Couldn't set the value of parameter '" + this.field.getName() + "' (" + this.getType().getName() + ") to '" + parameterValue + "' (" + parameterValue.getClass().getName() + ")!", e); } } public Set<Condition> getRequriedIfConditions() { RequiredIf[] requiredIfs = this.field.getAnnotationsByType(RequiredIf.class); if (requiredIfs == null || requiredIfs.length <= 0) { return Collections.emptySet(); } else { Set<Condition> conditions = Sets.newHashSet(); for (RequiredIf requiredIf : requiredIfs) { conditions.add(new Condition(requiredIf)); } return Collections.unmodifiableSet(conditions); } } public Set<Condition> getIgnoredIfConditions() { IgnoredIf[] ignoredIfs = this.field.getAnnotationsByType(IgnoredIf.class); if (ignoredIfs == null || ignoredIfs.length <= 0) { return Collections.emptySet(); } else { Set<Condition> conditions = Sets.newHashSet(); for (IgnoredIf ignoredIf : ignoredIfs) { conditions.add(new Condition(ignoredIf)); } return Collections.unmodifiableSet(conditions); } } public boolean isConditionallyRequiredIn(final AbstractConfiguration config) { checkNotNull(config, "Precondition violation - argument 'config' must not be NULL!"); Set<Condition> conditions = this.getRequriedIfConditions(); for (Condition condition : conditions) { if (condition.appliesTo(config)) { return true; } } return false; } public boolean isConditionallyIgnoredIn(final AbstractConfiguration config) { checkNotNull(config, "Precondition violation - argument 'config' must not be NULL!"); Set<Condition> conditions = this.getIgnoredIfConditions(); for (Condition condition : conditions) { if (condition.appliesTo(config)) { return true; } } return false; } public boolean hasValueIn(final AbstractConfiguration chronoConfig) { checkNotNull(chronoConfig, "Precondition violation - argument 'chronoConfig' must not be NULL!"); return this.getValue(chronoConfig) != null; } public Map<String, String> getValueAliases() { ValueAlias[] aliases = this.field.getAnnotationsByType(ValueAlias.class); Map<String, String> resultMap = Maps.newHashMap(); if (aliases == null || aliases.length <= 0) { return Collections.unmodifiableMap(resultMap); } for (ValueAlias alias : aliases) { String aliasString = alias.alias(); String mapToString = alias.mapTo(); if (resultMap.containsKey(aliasString) && resultMap.get(aliasString).equals(mapToString) == false) { throw new IllegalStateException("Defined multiple different aliases for value '" + aliasString + "' on field '" + this.field.getDeclaringClass() + "#" + this.field.getName() + "'!"); } resultMap.put(aliasString, mapToString); } return Collections.unmodifiableMap(resultMap); } public Object getValueAliasFor(final Object value) { Map<String, String> aliases = this.getValueAliases(); String alias = aliases.get(value); if (alias == null) { // no alias present; use original value return value; } else { // use alias return alias; } } public ParameterValueConverter getValueParser() { ValueConverter annotation = this.field.getAnnotation(ValueConverter.class); if (annotation == null) { return null; } Class<? extends ParameterValueConverter> parserClass = annotation.value(); try { Constructor<? extends ParameterValueConverter> constructor = parserClass.getConstructor(); return constructor.newInstance(); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { throw new IllegalStateException( "Unable to instantiate ParameterValueParser class '" + parserClass.getName() + "'!", e); } } public Method getEnumFactoryMethod() { if (this.getType().isEnum() == false) { return null; } EnumFactoryMethod annotation = this.field.getAnnotation(EnumFactoryMethod.class); if (annotation == null) { // no annotation is given, use the default 'valueOf' method that exists implicitly in each enum class try { return this.getType().getMethod("valueOf", String.class); } catch (NoSuchMethodException | SecurityException e) { throw new IllegalStateException( "Unable to access the 'valueOf' method of enum type '" + this.getType().getName() + "'!", e); } } String factoryMethodName = annotation.value(); try { Method method = this.getType().getMethod(factoryMethodName, String.class); if (Modifier.isStatic(method.getModifiers()) == false) { throw new IllegalStateException("The specified @EnumFactoryMethod [" + this.getType().getName() + " " + factoryMethodName + "(String)] must be static!"); } if (method.getReturnType().equals(this.getType()) == false) { throw new IllegalStateException("The specified @EnumFactoryMethod [" + factoryMethodName + "(String)] must have a return type of " + this.getType().getName() + "!"); } return method; } catch (NoSuchMethodException | SecurityException e) { throw new IllegalStateException( "The specified @EnumFactoryMethod [static " + this.getType().getName() + " " + factoryMethodName + "(String)] does not exist in " + this.getType().getName() + " or is not accessible!", e); } } @Override public String toString() { return "Parameter[key='" + this.getKey() + "', field=" + this.field.getDeclaringClass().getName() + "#" + this.field.getName() + ", type=" + this.getType().getSimpleName() + "]"; } }
9,549
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronosConfigurationUtil.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/configuration/ChronosConfigurationUtil.java
package org.chronos.common.configuration; import static com.google.common.base.Preconditions.*; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Iterator; import java.util.Map; import java.util.Set; import jakarta.annotation.PostConstruct; import org.apache.commons.configuration2.Configuration; import org.chronos.common.configuration.annotation.Namespace; import org.chronos.common.configuration.annotation.Parameter; import org.chronos.common.exceptions.ChronosConfigurationException; import org.chronos.common.util.ReflectionUtils; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ChronosConfigurationUtil { private static final Logger log = LoggerFactory.getLogger(ChronosConfigurationUtil.class); public static <T extends AbstractConfiguration> T build(final Configuration apacheConfiguration, final Class<T> configurationBeanClass) { checkNotNull(apacheConfiguration, "Precondition violation - argument 'apacheConfiguration' must not be NULL!"); checkNotNull(configurationBeanClass, "Precondition violation - argument 'configurationBeanClass' must not be NULL!"); T configurationBean = null; try { configurationBean = configurationBeanClass.getConstructor().newInstance(); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { throw new IllegalArgumentException("Configuration bean class must have a default constructor!", e); } final T bean = configurationBean; injectFieldValues(apacheConfiguration, bean); // check if the object has a post-construct method ReflectionUtils.getAnnotatedMethods(bean, PostConstruct.class).stream() .filter(m -> m.getParameterCount() == 0) .forEach(initMethod -> { try{ initMethod.setAccessible(true); initMethod.invoke(bean); }catch(Exception e){ throw new IllegalStateException("Failed to invoke @PostConstruct method '" + initMethod.getName() + "' on configuration bean!", e); } }); return bean; } private static void injectFieldValues(final Configuration apacheConfiguration, final AbstractConfiguration chronoConfig) { checkNotNull(apacheConfiguration, "Precondition violation - argument 'apacheConfiguration' must not be NULL!"); checkNotNull(chronoConfig, "Precondition violation - argument 'chronoConfig' must not be NULL!"); Set<Field> fields = ReflectionUtils.getAnnotatedFields(chronoConfig, Parameter.class); Map<String, ParameterMetadata> keyToParameter = Maps.newHashMap(); for (Field field : fields) { ParameterMetadata parameter = new ParameterMetadata(field); keyToParameter.put(parameter.getKey(), parameter); } Set<ParameterMetadata> unconfiguredParameters = Sets.newHashSet(); Set<ParameterMetadata> configuredParameters = Sets.newHashSet(); for (ParameterMetadata parameter : keyToParameter.values()) { String key = parameter.getKey(); Object defaultValue = parameter.getValue(chronoConfig); boolean keyConfigured = apacheConfiguration.containsKey(key); if (keyConfigured == false) { unconfiguredParameters.add(parameter); } else { Object configValue = null; if (apacheConfiguration.containsKey(key)) { configValue = apacheConfiguration.getProperty(key); } else { configValue = defaultValue; } // apply aliases (if any) configValue = parameter.getValueAliasFor(configValue); Object parameterValue = convertToParameterType(configValue, parameter); parameter.setValue(chronoConfig, parameterValue); configuredParameters.add(parameter); } } // check if all unconfigured parameters either are ignored or have default values Set<ParameterMetadata> missingParameters = getMissingParameters(unconfiguredParameters, chronoConfig); if (missingParameters.isEmpty() == false) { StringBuilder message = new StringBuilder(); message.append("The following properties are missing in your configuration:\n"); for (ParameterMetadata missingParameter : missingParameters) { message.append(missingParameter.getKey()); message.append("\n"); } throw new ChronosConfigurationException(message.toString()); } // check if all configured parameters are actually used (and display a warning if that's not the case) for (ParameterMetadata parameter : configuredParameters) { if (parameter.isConditionallyIgnoredIn(chronoConfig)) { log.warn("Configuration issue: the parameter '" + parameter.getKey() + "' in your configuration is ignored due to an overriding other parameter." + " Please refer to the documentation."); } } // check if there are some parameters in our namespace that are not mapped at all checkForUnknownParametersInNamespace(apacheConfiguration, chronoConfig, keyToParameter); } @SuppressWarnings({"rawtypes"}) private static Object convertToParameterType(final Object setting, final ParameterMetadata parameter) { if (parameter.getType().isInstance(setting)) { // no conversion neccessary return setting; } ParameterValueConverter parser = parameter.getValueParser(); if (parser != null) { // always use the parser if available try { return parser.convert(setting); } catch (Exception e) { throw new ChronosConfigurationException("Custom parser '" + parser.getClass().getName() + "' failed to parse value '" + setting + "' for field '" + parameter.getType().getDeclaringClass() + "#" + parameter.getType().getName() + "'!", e); } } Class<?> parameterType = parameter.getType(); if (String.class.equals(parameterType)) { return setting; } else if (Enum.class.isAssignableFrom(parameterType)) { Class enumClass = parameterType; try { Method factoryMethod = parameter.getEnumFactoryMethod(); return factoryMethod.invoke(null, String.valueOf(setting)); } catch (IllegalArgumentException | InvocationTargetException e) { // given value is no proper enum constant throw new ChronosConfigurationException("The value '" + setting + "' for parameter '" + parameter.getKey() + "' is no valid value. Valid values include: " + Arrays.toString(enumClass.getEnumConstants()), e); } catch (IllegalAccessException e) { throw new ChronosConfigurationException( "Unable to access static enum factory method for class '" + enumClass.getName() + "'!", e); } } else if (ReflectionUtils.isPrimitiveOrWrapperClass(parameterType)) { return ReflectionUtils.parsePrimitive(String.valueOf(setting), parameterType); } else { throw new ChronosConfigurationException("Unable to assign value '" + setting + "' (" + setting.getClass().getName() + ") to " + parameter + "!"); } } private static Set<ParameterMetadata> getMissingParameters(final Set<ParameterMetadata> unassigned, final AbstractConfiguration chronoConfig) { Set<ParameterMetadata> missingParameters = Sets.newHashSet(); for (ParameterMetadata parameter : unassigned) { if (parameter.isOptional()) { // parameter is optional; may be left unset continue; } if (parameter.isConditionallyRequired() && parameter.isConditionallyRequiredIn(chronoConfig) == false) { // parameter is conditionally required, but our config doesn't require it; may be left unset continue; } if (parameter.hasValueIn(chronoConfig)) { // parameter is given by default value continue; } if (parameter.isConditionallyIgnored() && parameter.isConditionallyIgnoredIn(chronoConfig)) { // parameter is ignored in our current setup continue; } // parameter is indeed missing missingParameters.add(parameter); } return missingParameters; } private static void checkForUnknownParametersInNamespace(final Configuration apacheConfiguration, final AbstractConfiguration chronoConfig, final Map<String, ParameterMetadata> keyToParameter) { String namespace = getNamespace(chronoConfig); if (namespace == null) { return; } Iterator<String> keys = apacheConfiguration.getKeys(); while (keys.hasNext()) { String key = keys.next(); if (key.startsWith(namespace + ".")) { ParameterMetadata parameter = keyToParameter.get(key); if (parameter == null) { // unknown parameter log.warn("Configuration issue: the parameter '" + key + "' is unknown, but in the namespace '" + namespace + "' - please check the spelling."); } } } } private static String getNamespace(final AbstractConfiguration configuration) { Namespace annotation = ReflectionUtils.getClassAnnotationRecursively(configuration.getClass(), Namespace.class); if (annotation == null) { return null; } String namespace = annotation.value().trim(); if (namespace == null || namespace.isEmpty()) { return null; } return namespace; } }
10,628
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronosConfiguration.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/configuration/ChronosConfiguration.java
package org.chronos.common.configuration; import java.util.Map; import org.apache.commons.configuration2.Configuration; /** * This is the basic interface for all configuration classes in Chronos. * * <p> * The primary purpose of this interface (aside from acting as a base class) is to offer methods that convert the * configuration into a variety of output formats, such as an Apache Commons {@link Configuration} object. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public interface ChronosConfiguration { /** * Converts the contents of this configuration into an Apache Commons {@link Configuration} object. * * <p> * The returned object will receive a copy of the internal values, therefore any modifications to the returned * configuration will have no impact on the internal state, and vice versa. * * @return The Apache Commons Configuration object. May be empty, but never <code>null</code>. */ public Configuration asCommonsConfiguration(); /** * Converts the contents of this configuration into a regular <code>java.util.{@link Map}</code>. * * <p> * The returned map will receive a copy of the internal values, therefore any modifications to the returned map will * have no impact on the internal state, and vice versa. * * @return This configuration, converted into a regular map. May be empty, but never <code>null</code>. */ public Map<String, Object> asMap(); }
1,459
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
Condition.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/configuration/Condition.java
package org.chronos.common.configuration; import static com.google.common.base.Preconditions.*; import org.chronos.common.configuration.annotation.IgnoredIf; import org.chronos.common.configuration.annotation.RequiredIf; import org.chronos.common.exceptions.UnknownEnumLiteralException; public class Condition { private final String field; private final Comparison comparison; private final String value; public Condition(final RequiredIf requiredIf) { checkNotNull(requiredIf, "Precondition violation - argument 'requiredIf' must not be NULL!"); this.field = requiredIf.field(); this.comparison = requiredIf.comparison(); this.value = requiredIf.compareValue(); } public Condition(final IgnoredIf ignoredIf) { checkNotNull(ignoredIf, "Precondition violation - argument 'ignoredIf' must not be NULL!"); this.field = ignoredIf.field(); this.comparison = ignoredIf.comparison(); this.value = ignoredIf.compareValue(); } public boolean appliesTo(final AbstractConfiguration config) { checkNotNull(config, "Precondition violation - argument 'config' must not be NULL!"); ParameterMetadata parameter = config.getMetadataOfField(this.field); Object value = parameter.getValue(config); switch (this.comparison) { case IS_SET: return value != null; case IS_NOT_SET: return value == null; case IS_SET_TO: return this.value.equals(value) || this.value.toString().equals(String.valueOf(value)); case IS_NOT_SET_TO: return this.value.toString().equals(String.valueOf(value)) == false; default: throw new UnknownEnumLiteralException(this.comparison); } } }
1,611
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
Comparison.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/configuration/Comparison.java
package org.chronos.common.configuration; public enum Comparison { IS_SET, IS_NOT_SET, IS_SET_TO, IS_NOT_SET_TO }
118
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ParameterValueConverter.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/configuration/ParameterValueConverter.java
package org.chronos.common.configuration; public interface ParameterValueConverter { public Object convert(Object rawParameter); }
135
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AbstractConfiguration.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/configuration/AbstractConfiguration.java
package org.chronos.common.configuration; import java.lang.reflect.Field; import java.util.Collections; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.apache.commons.configuration2.BaseConfiguration; import org.apache.commons.configuration2.Configuration; import org.chronos.common.configuration.annotation.Parameter; import org.chronos.common.util.ReflectionUtils; import com.google.common.collect.Maps; public abstract class AbstractConfiguration implements ChronosConfiguration { private transient Set<ParameterMetadata> metadataCache = null; public Set<String> getAllParameterKeys() { return this.getMetadata().stream().map(p -> p.getKey()).collect(Collectors.toSet()); } public Set<ParameterMetadata> getMetadata() { if (this.metadataCache == null) { Set<Field> fields = ReflectionUtils.getAnnotatedFields(this.getClass(), Parameter.class); this.metadataCache = fields.stream().map(field -> new ParameterMetadata(field)).collect(Collectors.toSet()); this.metadataCache = Collections.unmodifiableSet(this.metadataCache); } return Collections.unmodifiableSet(this.metadataCache); } public ParameterMetadata getMetadataOfParameter(final String parameterKey) { Optional<ParameterMetadata> maybeParam = this.getMetadata().stream() .filter(p -> p.getKey().equals(parameterKey)).findAny(); return maybeParam.orElse(null); } public ParameterMetadata getMetadataOfField(final String fieldName) { Set<Field> fields = ReflectionUtils.getAnnotatedFields(this.getClass(), Parameter.class); Optional<Field> maybeField = fields.stream().filter(f -> f.getName().equals(fieldName)).findAny(); if (maybeField.isPresent()) { return new ParameterMetadata(maybeField.get()); } else { return null; } } @Override public Map<String, Object> asMap() { Map<String, Object> map = Maps.newHashMap(); Set<String> keys = this.getAllParameterKeys(); for (String key : keys) { Object value = this.getMetadataOfParameter(key).getValue(this); map.put(key, value); } return map; } @Override public Configuration asCommonsConfiguration() { BaseConfiguration configuration = new BaseConfiguration(); for (Entry<String, Object> entry : this.asMap().entrySet()) { configuration.addProperty(entry.getKey(), entry.getValue()); } return configuration; } }
2,414
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ParameterValueConverters.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/configuration/ParameterValueConverters.java
package org.chronos.common.configuration; import java.io.File; public class ParameterValueConverters { public static class StringToFileConverter implements ParameterValueConverter { @Override public Object convert(final Object rawParameter) { String path = String.valueOf(rawParameter); File file = new File(path); return file; } } }
356
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
RequiredIf.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/configuration/annotation/RequiredIf.java
package org.chronos.common.configuration.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.chronos.common.configuration.Comparison; @Documented @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Repeatable(RequiredIfConditions.class) public @interface RequiredIf { public String field(); public Comparison comparison(); public String compareValue() default ""; }
600
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
Namespace.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/configuration/annotation/Namespace.java
package org.chronos.common.configuration.annotation; 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 Namespace { public String value(); public boolean warningOnUnknownParameters() default true; }
448
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EnumFactoryMethod.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/configuration/annotation/EnumFactoryMethod.java
package org.chronos.common.configuration.annotation; 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.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface EnumFactoryMethod { public String value(); }
397
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
IgnoredIfConditions.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/configuration/annotation/IgnoredIfConditions.java
package org.chronos.common.configuration.annotation; 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.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface IgnoredIfConditions { IgnoredIf[] value(); }
397
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ValueAliases.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/configuration/annotation/ValueAliases.java
package org.chronos.common.configuration.annotation; 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.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface ValueAliases { ValueAlias[] value(); }
390
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ValueConverter.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/configuration/annotation/ValueConverter.java
package org.chronos.common.configuration.annotation; 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; import org.chronos.common.configuration.ParameterValueConverter; @Documented @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface ValueConverter { public Class<? extends ParameterValueConverter> value(); }
494
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ValueAlias.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/configuration/annotation/ValueAlias.java
package org.chronos.common.configuration.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Documented @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Repeatable(ValueAliases.class) public @interface ValueAlias { public String alias(); public String mapTo(); }
487
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
Parameter.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/configuration/annotation/Parameter.java
package org.chronos.common.configuration.annotation; 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.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Parameter { public String key() default ""; public boolean optional() default false; }
441
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
RequiredIfConditions.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/configuration/annotation/RequiredIfConditions.java
package org.chronos.common.configuration.annotation; 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.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface RequiredIfConditions { RequiredIf[] value(); }
399
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
IgnoredIf.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/configuration/annotation/IgnoredIf.java
package org.chronos.common.configuration.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.chronos.common.configuration.Comparison; @Documented @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Repeatable(IgnoredIfConditions.class) public @interface IgnoredIf { public String field(); public Comparison comparison(); public String compareValue() default ""; }
598
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronosVersion.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/version/ChronosVersion.java
package org.chronos.common.version; import static com.google.common.base.Preconditions.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.chronos.common.buildinfo.ChronosBuildInfo; public final class ChronosVersion implements Comparable<ChronosVersion> { // ===================================================================================================================== // OTHER CONSTANTS // ===================================================================================================================== private static final String CHRONOS_VERSION_REGEX = "([0-9]+)\\.([0-9]+)\\.([0-9]+)([-\\.:]([a-zA-Z]+))?"; private static final Pattern CHRONOS_VERSION_PATTERN = Pattern.compile(CHRONOS_VERSION_REGEX, Pattern.CASE_INSENSITIVE); // ===================================================================================================================== // STATIC FACTORY METHODS // ===================================================================================================================== public static ChronosVersion parse(final String stringVersion) { checkNotNull(stringVersion, "Precondition violation - argument 'stringVersion' must not be NULL!"); Matcher matcher = CHRONOS_VERSION_PATTERN.matcher(stringVersion); if (matcher.matches() == false) { throw new IllegalArgumentException( "The given string is no valid Chronos Version: '" + stringVersion + "'!"); } int majorVersion = 0; int minorVersion = 0; int patchVersion = 0; VersionKind kind = null; try { // NOTE: Group 0 is the entire match! majorVersion = Integer.parseInt(matcher.group(1)); minorVersion = Integer.parseInt(matcher.group(2)); patchVersion = Integer.parseInt(matcher.group(3)); String kindString = matcher.group(5); if (kindString == null || kindString.trim().isEmpty()) { // missing "kind" information is interpreted as RELEASE kind = VersionKind.RELEASE; } else { kind = VersionKind.parse(kindString); } } catch (IllegalArgumentException e) { throw new IllegalArgumentException( "The given string is no valid Chronos Version: '" + stringVersion + "'!"); } return new ChronosVersion(majorVersion, minorVersion, patchVersion, kind); } public static ChronosVersion getCurrentVersion() { String buildVersion = ChronosBuildInfo.getConfiguration().getBuildVersion(); return ChronosVersion.parse(buildVersion); } // ===================================================================================================================== // FIELDS // ===================================================================================================================== private final int majorVersion; private final int minorVersion; private final int patchVersion; private final VersionKind versionKind; // ===================================================================================================================== // CONSTRUCTOR // ===================================================================================================================== public ChronosVersion(final int major, final int minor, final int patch, final VersionKind kind) { checkArgument(major >= 0, "Precondition violation - argument 'major' must not be negative!"); checkArgument(minor >= 0, "Precondition violation - argument 'minor' must not be negative!"); checkArgument(patch >= 0, "Precondition violation - argument 'patch' must not be negative!"); checkNotNull(kind, "Precondition violation - argument 'kind' must not be NULL!"); this.majorVersion = major; this.minorVersion = minor; this.patchVersion = patch; this.versionKind = kind; } // ===================================================================================================================== // GETTERS & SETTERS // ===================================================================================================================== public int getMajorVersion() { return this.majorVersion; } public int getMinorVersion() { return this.minorVersion; } public int getPatchVersion() { return this.patchVersion; } public VersionKind getVersionKind() { return this.versionKind; } public boolean isReadCompatibleWith(final ChronosVersion other) { checkNotNull(other, "Precondition violation - argument 'other' must not be NULL!"); if (this.compareTo(other) >= 0) { // we can read past revisions return true; } // we define "read compatibility" for DBs written by newer versions as "having the same major AND minor version // here. if (this.getMajorVersion() == other.getMajorVersion() && this.getMinorVersion() == other.getMinorVersion()) { return true; } else { return false; } } public boolean isSmallerThan(final ChronosVersion other) { return this.compareTo(other) < 0; } public boolean isSmallerThanOrEqualTo(final ChronosVersion other) { return this.compareTo(other) <= 0; } public boolean isGreaterThan(final ChronosVersion other) { return this.compareTo(other) > 0; } public boolean isGreaterThanOrEqualTo(final ChronosVersion other) { return this.compareTo(other) >= 0; } // ===================================================================================================================== // COMPARATOR // ===================================================================================================================== @Override public int compareTo(final ChronosVersion o) { if (o == null) { return 1; } // first order by major version if (this.getMajorVersion() > o.getMajorVersion()) { return 1; } if (this.getMajorVersion() < o.getMajorVersion()) { return -1; } // then order by minor version if (this.getMinorVersion() > o.getMinorVersion()) { return 1; } if (this.getMinorVersion() < o.getMinorVersion()) { return -1; } // then order by patch version if (this.getPatchVersion() > o.getPatchVersion()) { return 1; } if (this.getPatchVersion() < o.getPatchVersion()) { return -1; } // ultimately, check the version kinds (RELEASE > SNAPSHOT) if (this.getVersionKind().equals(VersionKind.RELEASE) && o.getVersionKind().equals(VersionKind.SNAPSHOT)) { return 1; } if (this.getVersionKind().equals(VersionKind.SNAPSHOT) && o.getVersionKind().equals(VersionKind.RELEASE)) { return -1; } // in any other case, they HAVE to be equal return 0; }; // ===================================================================================================================== // HASH CODE & EQUALS // ===================================================================================================================== @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + this.majorVersion; result = prime * result + this.minorVersion; result = prime * result + this.patchVersion; result = prime * result + (this.versionKind == null ? 0 : this.versionKind.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; } ChronosVersion other = (ChronosVersion) obj; if (this.majorVersion != other.majorVersion) { return false; } if (this.minorVersion != other.minorVersion) { return false; } if (this.patchVersion != other.patchVersion) { return false; } if (this.versionKind != other.versionKind) { return false; } return true; } // ===================================================================================================================== // TO STRING // ===================================================================================================================== @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(this.getMajorVersion()); builder.append("."); builder.append(this.getMinorVersion()); builder.append("."); builder.append(this.getPatchVersion()); builder.append("-"); builder.append(this.getVersionKind()); return builder.toString(); } }
8,190
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
VersionKind.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/version/VersionKind.java
package org.chronos.common.version; import static com.google.common.base.Preconditions.*; public enum VersionKind { // ===================================================================================================================== // ENUM CONSTANTS // ===================================================================================================================== SNAPSHOT("SNAPSHOT"), RELEASE("RELEASE"); // ===================================================================================================================== // STATIC FACTORY METHODS // ===================================================================================================================== public static VersionKind parse(final String string) { checkNotNull(string, "Precondition violation - argument 'string' must not be NULL!"); String raw = string.toLowerCase().trim(); for (VersionKind kind : VersionKind.values()) { if (kind.toString().equalsIgnoreCase(raw)) { return kind; } } throw new IllegalArgumentException("The given argument string is not a Version Kind: '" + string + "'!"); } // ===================================================================================================================== // FIELDS // ===================================================================================================================== private String stringRepresentation; // ===================================================================================================================== // CONSTRUCTOR // ===================================================================================================================== private VersionKind(final String stringRepresentation) { this.stringRepresentation = stringRepresentation; } // ===================================================================================================================== // GETTERS & SETTERS // ===================================================================================================================== @Override public String toString() { return this.stringRepresentation; } }
2,141
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AbstractChronoBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/builder/AbstractChronoBuilder.java
package org.chronos.common.builder; import static com.google.common.base.Preconditions.*; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Collections; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import org.apache.commons.configuration2.BaseConfiguration; import org.apache.commons.configuration2.Configuration; import org.chronos.common.exceptions.ChronosException; import com.google.common.collect.Maps; public class AbstractChronoBuilder<SELF extends ChronoBuilder<?>> implements ChronoBuilder<SELF> { protected final Map<String, String> properties; public AbstractChronoBuilder() { this.properties = Maps.newHashMap(); } @Override @SuppressWarnings("unchecked") public SELF withProperty(final String key, final String value) { checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); checkNotNull(value, "Precondition violation - argument 'value' must not be NULL!"); this.properties.put(key, value); return (SELF) this; } protected String getProperty(final String key) { return this.properties.get(key); } @Override public Map<String, String> getProperties() { return Collections.unmodifiableMap(Maps.newHashMap(this.properties)); } protected Configuration getPropertiesAsConfiguration() { Map<String, String> properties = this.getProperties(); Configuration config = new BaseConfiguration(); for (Entry<String, String> entry : properties.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); config.setProperty(key, value); } return config; } @Override @SuppressWarnings("unchecked") public SELF withPropertiesFile(final File file) { checkNotNull(file, "Precondition violation - argument 'file' must not be NULL!"); checkArgument(file.isFile(), "Precondition violation - argument 'file' must be a file (not a directory)!"); checkArgument(file.exists(), "Precondition violation - argument 'file' must refer to an existing file!"); checkArgument(file.getName().endsWith(".properties"), "Precondition violation - argument 'file' must specify a file name that ends with '.properties'!"); Properties properties = new Properties(); try { FileReader reader = new FileReader(file); properties.load(reader); for (Entry<Object, Object> entry : properties.entrySet()) { String key = String.valueOf(entry.getKey()); String value = String.valueOf(entry.getValue()); this.properties.put(key, value); } reader.close(); } catch (IOException ioe) { throw new ChronosException("Failed to read properties file '" + file.getAbsolutePath() + "'!", ioe); } return (SELF) this; } @Override public SELF withPropertiesFile(final String filePath) { checkNotNull(filePath, "Precondition violation - argument 'filePath' must not be NULL!"); File propertiesFile = new File(filePath); return this.withPropertiesFile(propertiesFile); } }
2,962
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/builder/ChronoBuilder.java
package org.chronos.common.builder; import java.io.File; import java.util.Map; /** * A generic builder interface that allows setting properties as key-value pairs. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * * @param <SELF> * The dynamic type of <code>this</code> to return for method chaining. */ public interface ChronoBuilder<SELF extends ChronoBuilder<?>> { /** * Sets the given property on this builder to the given value. * * @param key * The key to set. Must not be <code>null</code>. * @param value * The value to set. Must not be <code>null</code>. * @return <code>this</code> (for fluent method chaining). */ public SELF withProperty(String key, String value); /** * Loads the given properties file as configuration for this builder. * * <p> * The file must fulfill all of the following conditions: * <ul> * <li>The file must be a file, not a directory. * <li>The file must exist. * <li>The file must be accessible. * <li>The file name must end with <code>.properties</code> * <li>The file contents must follow the default {@link java.util.Properties} format. * </ul> * * @param file * The properties file to read. Must not be <code>null</code>, must adhere to all of the conditions * stated above. * @return <code>this</code> (for fluent method chaining). */ public SELF withPropertiesFile(File file); /** * Loads the properties file via the given path as configuration for this builder. * * <p> * The file given by the path must fulfill all of the following conditions: * <ul> * <li>The file must be a file, not a directory. * <li>The file must exist. * <li>The file must be accessible. * <li>The file name must end with <code>.properties</code> * <li>The file contents must follow the default {@link java.util.Properties} format. * </ul> * * @param filePath * The file path to the properties file to read. Must not be <code>null</code>, must adhere to all of the * conditions stated above. * @return <code>this</code> (for fluent method chaining). */ public SELF withPropertiesFile(String filePath); /** * Returns an unmodifiable map of all properties which have been collected on this builder so far. * * <p> * The returned map is an immutable snapshot copy of the current state. * </p> * * @return The properties collected by this builder, as an immutable map snapshot. May be empty, but never <code>null</code>. */ public Map<String, String> getProperties(); }
2,606
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
CacheUtils.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/util/CacheUtils.java
package org.chronos.common.util; import static com.google.common.base.Preconditions.*; import java.util.function.Function; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; /** * This is a very simple utility class that eases the syntactical handling of the Guava {@link CacheBuilder}. * * <p> * Please use one of the <code>static</code> methods provided by this class. Do not instantiate it. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public class CacheUtils { /** * Builds a new Least-Recently-Used cache with the given size and loading function. * * @param size * The size of the cache, i.e. the maximum number of elements that can be present. Must be strictly larger than zero. Loading an element that would exceed the given limit will cause the least-recently-used element to be evicted from the cache. * @param loadingFunction * The function that loads the value for the given key. Must not be <code>null</code>. * * @return The newly created cache. Never <code>null</code>. */ public static <K, V> LoadingCache<K, V> buildLRU(final int size, final Function<K, V> loadingFunction) { checkArgument(size > 0, "Precondition violation - argument 'size' must be greater than zero!"); checkNotNull(loadingFunction, "Precondition violation - argument 'loadingFunction' must not be NULL!"); return CacheBuilder.newBuilder().maximumSize(size).build(new CacheLoader<K, V>() { @Override public V load(final K key) throws Exception { V value = loadingFunction.apply(key); if(value == null){ throw new Exception("No element with ID '" + key + "'!"); } return value; } }); } /** * Builds a new cache with weakly referenced values. * * @param loadingFunction The function that loads the value for a given key in case of a cache miss. Must not be <code>null</code>. * @param <K> The type of the keys * @param <V> The type of the values * @return The newly created cache instance. Never <code>null</code>. */ public static <K, V> LoadingCache<K, V> buildWeak(final Function<K, V> loadingFunction) { checkNotNull(loadingFunction, "Precondition violation - argument 'loadingFunction' must not be NULL!"); return CacheBuilder.newBuilder().weakValues().build(new CacheLoader<K, V>() { @Override public V load(final K key) throws Exception { V value = loadingFunction.apply(key); if(value == null){ throw new Exception("No element with ID '" + key + "'!"); } return value; } }); } }
2,634
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ClasspathUtils.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/util/ClasspathUtils.java
package org.chronos.common.util; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import com.google.common.base.Preconditions; public class ClasspathUtils { public static void printClasspathJars() { ClassLoader cl = Thread.currentThread().getContextClassLoader(); URL[] urls = ((URLClassLoader) cl).getURLs(); for (URL url : urls) { System.out.println(url.getFile()); } } public static URL getURIFromResourceByName(final String resourceName) { return Thread.currentThread().getContextClassLoader().getResource(resourceName); } public static String getPathFromResourceByName(final String resourceName) { URL url = Thread.currentThread().getContextClassLoader().getResource(resourceName); if (url == null) { return null; } String path = url.toExternalForm(); return path.substring(0, path.length() - resourceName.length()); } /** * Checks if there is a resource with the given name on the Java classpath. * * @param resourceName * The name of the resource to check. Must not be <code>null</code>. Must contain a non-whitespace character. * @return <code>true</code> if the given name refers to an existing classpath resource, otherwise <code>false</code>. */ public static boolean isClasspathResource(final String resourceName) { Preconditions.checkNotNull(resourceName, "Cannot check classpath existence of resource with name NULL!"); Preconditions.checkArgument(resourceName.trim().isEmpty() == false, "Cannot check classpath existence of resource with name EMPTY!"); URL url = Thread.currentThread().getContextClassLoader().getResource(resourceName); return url != null; } public static File getResourceAsFile(final String resourceName) throws IOException { URL url = getURIFromResourceByName(resourceName); if (url == null) { return null; } // NOTE: url.getFile() is *dangerous* because space characters in the filepath will be encoded as // '%20', which will lead to failure later on (FileNotFoundException). // Therefore, instead of: // --- new File(url.getFile()); // it is safer to use: // --- new File(url.toURI()); try { return new File(url.toURI()); } catch (URISyntaxException e) { throw new IOException("Unable to read file resource '" + resourceName + "'! See root cause for details.", e); } catch (IllegalArgumentException e) { // most like the file is zipped/war'ed/jar'ed, buildLRU temporary file from stream int extensionIndex = resourceName.lastIndexOf("."); String tmpExtension = resourceName.substring(extensionIndex); File tmpResource = null; try { // input stream to tmp file InputStream resourceInputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourceName); tmpResource = File.createTempFile("tmp", tmpExtension); Files.copy(resourceInputStream, tmpResource.toPath(), StandardCopyOption.REPLACE_EXISTING); tmpResource.deleteOnExit(); return tmpResource; } catch (IOException ioex) { String tmpFilePath = "<unknown>"; if (tmpResource != null) { tmpFilePath = tmpResource.getAbsolutePath(); } throw new IOException("Failed to read file resource '" + resourceName + "' from JAR, copied it to temp directory (" + tmpFilePath + "), but still failed to load it! See root cause for details.", ioex); } } } }
3,526
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ReflectionUtils.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/util/ReflectionUtils.java
package org.chronos.common.util; import static com.google.common.base.Preconditions.*; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.common.collect.Sets; import org.chronos.common.configuration.AbstractConfiguration; public final class ReflectionUtils { private static final Set<Class<?>> WRAPPER_CLASSES; private static final Map<Class<?>, Class<?>> WRAPPER_CLASS_TO_PRIMITIVE_CLASS; private static final Map<Class<?>, Class<?>> PRIMITIVE_CLASS_TO_WRAPPER_CLASS; static { BiMap<Class<?>, Class<?>> wrapperToPrimitive = HashBiMap.create(); wrapperToPrimitive.put(Boolean.class, boolean.class); wrapperToPrimitive.put(Byte.class, byte.class); wrapperToPrimitive.put(Short.class, short.class); wrapperToPrimitive.put(Character.class, char.class); wrapperToPrimitive.put(Integer.class, int.class); wrapperToPrimitive.put(Long.class, long.class); wrapperToPrimitive.put(Float.class, float.class); wrapperToPrimitive.put(Double.class, double.class); WRAPPER_CLASS_TO_PRIMITIVE_CLASS = Collections.unmodifiableMap(wrapperToPrimitive); PRIMITIVE_CLASS_TO_WRAPPER_CLASS = Collections.unmodifiableMap(wrapperToPrimitive.inverse()); WRAPPER_CLASSES = Collections.unmodifiableSet(wrapperToPrimitive.keySet()); } public static Set<Field> getAllFields(final Object object) { checkNotNull(object, "Precondition violation - argument 'object' must not be NULL!"); return getAllFields(object.getClass()); } public static Set<Field> getAllFields(final Class<?> clazz) { checkNotNull(clazz, "Precondition violation - argument 'clazz' must not be NULL!"); Set<Field> allFields = Sets.newHashSet(); Class<?> currentClass = clazz; while (true) { if (clazz.equals(Object.class)) { // we reached the inheritance root return Collections.unmodifiableSet(allFields); } Field[] localFields = currentClass.getDeclaredFields(); for (Field field : localFields) { allFields.add(field); } currentClass = currentClass.getSuperclass(); } } @SafeVarargs public static Set<Field> getAnnotatedFields(final Object object, final Class<? extends Annotation>... annotations) { checkNotNull(object, "Precondition violation - argument 'object' must not be NULL!"); return getAnnotatedFields(object.getClass(), annotations); } public static Set<Field> getAnnotatedFields(final Object object, final Collection<Class<? extends Annotation>> annotations) { checkNotNull(object, "Precondition violation - argument 'object' must not be NULL!"); checkNotNull(annotations, "Precondition violation - argument 'annotations' must not be NULL!"); return getAnnotatedFields(object.getClass(), annotations); } @SafeVarargs public static Set<Field> getAnnotatedFields(final Class<?> clazz, final Class<? extends Annotation>... annotations) { checkNotNull(clazz, "Precondition violation - argument 'clazz' must not be NULL!"); if (annotations == null || annotations.length <= 0) { return getAllFields(clazz); } Set<Class<? extends Annotation>> annotationSet = Sets.newHashSet(annotations); return getAnnotatedFields(clazz, annotationSet); } public static Set<Field> getAnnotatedFields(final Class<?> clazz, final Collection<Class<? extends Annotation>> annotations) { checkNotNull(clazz, "Precondition violation - argument 'clazz' must not be NULL!"); checkNotNull(annotations, "Precondition violation - argument 'annotations' must not be NULL!"); if (annotations.isEmpty()) { return getAllFields(clazz); } Set<Field> allFields = Sets.newHashSet(); Class<?> currentClass = clazz; while (currentClass.equals(Object.class) == false) { Field[] localFields = currentClass.getDeclaredFields(); for (Field field : localFields) { Annotation[] fieldAnnotations = field.getAnnotations(); for (Annotation annotation : fieldAnnotations) { Class<? extends Annotation> annotationClass = annotation.annotationType(); if (annotations.contains(annotationClass)) { allFields.add(field); break; } } } currentClass = currentClass.getSuperclass(); } return Collections.unmodifiableSet(allFields); } public static <T extends Annotation> T getClassAnnotationRecursively(final Class<?> clazz, final Class<T> annotation) { checkNotNull(clazz, "Precondition violation - argument 'clazz' must not be NULL!"); checkNotNull(annotation, "Precondition violation - argument 'annotation' must not be NULL!"); Class<?> currentClass = clazz; while (currentClass.equals(Object.class) == false) { T annotationInstance = currentClass.getAnnotation(annotation); if (annotationInstance != null) { return annotationInstance; } currentClass = currentClass.getSuperclass(); } return null; } public static boolean isWrapperClass(final Class<?> clazz) { checkNotNull(clazz, "Precondition violation - argument 'clazz' must not be NULL!"); return WRAPPER_CLASSES.contains(clazz); } public static boolean isPrimitiveClass(final Class<?> clazz) { checkNotNull(clazz, "Precondition violation - argument 'clazz' must not be NULL!"); return clazz.isPrimitive(); } public static boolean isPrimitiveOrWrapperClass(final Class<?> clazz) { checkNotNull(clazz, "Precondition violation - argument 'clazz' must not be NULL!"); return isPrimitiveClass(clazz) || isWrapperClass(clazz); } public static Class<?> getWrapperClass(final Class<?> clazz) { checkNotNull(clazz, "Precondition violation - argument 'clazz' must not be NULL!"); if (isPrimitiveClass(clazz)) { return PRIMITIVE_CLASS_TO_WRAPPER_CLASS.get(clazz); } else { return clazz; } } public static Class<?> getPrimitiveClass(final Class<?> clazz) { checkNotNull(clazz, "Precondition violation - argument 'clazz' must not be NULL!"); if (isWrapperClass(clazz)) { return WRAPPER_CLASS_TO_PRIMITIVE_CLASS.get(clazz); } else { return clazz; } } public static Object parsePrimitive(final String string, final Class<?> clazz) { checkNotNull(string, "Precondition violation - argument 'string' must not be NULL!"); checkNotNull(clazz, "Precondition violation - argument 'clazz' must not be NULL!"); // eliminate wrapper class, if any Class<?> primitiveClass = getPrimitiveClass(clazz); if (primitiveClass.isPrimitive() == false) { throw new IllegalArgumentException( "Cannot parse primitive - the given class is neither primitive nor a wrapper: '" + clazz.getName() + "'!"); } if (primitiveClass.equals(boolean.class)) { return Boolean.parseBoolean(string); } else if (primitiveClass.equals(byte.class)) { return Byte.parseByte(string); } else if (primitiveClass.equals(short.class)) { return Short.parseShort(string); } else if (primitiveClass.equals(char.class)) { if (string.length() != 1) { throw new NumberFormatException("The string '" + string + "' cannot be converted into a Character!"); } return string.charAt(0); } else if (primitiveClass.equals(int.class)) { return Integer.parseInt(string); } else if (primitiveClass.equals(long.class)) { return Long.parseLong(string); } else if (primitiveClass.equals(float.class)) { return Float.parseFloat(string); } else if (primitiveClass.equals(double.class)) { return Double.parseDouble(string); } throw new IllegalArgumentException( "Unable to parse primitive - unknown primitive class: '" + primitiveClass.getName() + "'!"); } public static Method getDeclaredMethod(final Class<?> clazz, final String methodName) { checkNotNull(clazz, "Precondition violation - argument 'clazz' must not be NULL!"); checkNotNull(methodName, "Precondition violation - argument 'methodName' must not be NULL!"); Class<?> currentClass = clazz; while (currentClass.equals(Object.class) == false) { Method[] methods = currentClass.getDeclaredMethods(); for (Method method : methods) { if (method.getName().equals(methodName)) { return method; } } currentClass = currentClass.getSuperclass(); } return null; } public static Field getDeclaredField(final Class<?> clazz, final String fieldName) { checkNotNull(clazz, "Precondition violation - argument 'clazz' must not be NULL!"); checkNotNull(fieldName, "Precondition violation - argument 'fieldName' must not be NULL!"); Class<?> currentClass = clazz; while (currentClass.equals(Object.class) == false) { Field[] fields = currentClass.getDeclaredFields(); for (Field field : fields) { if (field.getName().equals(fieldName)) { return field; } } currentClass = currentClass.getSuperclass(); } return null; } public static <T> T instantiate(final Class<T> clazz) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { checkNotNull(clazz, "Precondition violation - argument 'clazz' must not be NULL!"); Constructor<T> constructor = clazz.getConstructor(); if (Modifier.isPublic(constructor.getModifiers()) == false) { constructor.setAccessible(true); } return constructor.newInstance(); } public static boolean isLongCompatible(final Object value) { return value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long; } public static long asLong(final Object value) { if (value == null) { throw new NullPointerException("Cannot convert NULL to java.lang.Long!"); } if (!isLongCompatible(value)) { throw new IllegalArgumentException("Cannot convert " + value.getClass().getName() + " to java.lang.Long!"); } Number number = (Number) value; return number.longValue(); } public static boolean isDoubleCompatible(final Object value) { return value instanceof Number; } public static double asDouble(final Object value) { if (value == null) { throw new NullPointerException("Cannot convert NULL to java.lang.Double!"); } if (!isDoubleCompatible(value)) { throw new IllegalArgumentException("Cannot convert " + value.getClass().getName() + " to java.lang.Double!"); } Number number = (Number) value; return number.doubleValue(); } public static Set<Method> getAllMethods(final Object object) { checkNotNull(object, "Precondition violation - argument 'object' must not be NULL!"); return getAllMethods(object.getClass()); } public static Set<Method> getAllMethods(final Class<?> clazz){ checkNotNull(clazz, "Precondition violation - argument 'clazz' must not be NULL!"); Set<Method> resultSet = Sets.newHashSet(); Class<?> currentClass = clazz; while(currentClass != Object.class){ Method[] declaredMethods = currentClass.getDeclaredMethods(); Collections.addAll(resultSet, declaredMethods); currentClass = currentClass.getSuperclass(); } return resultSet; } public static Set<Method> getAnnotatedMethods(final Object object, final Class<? extends Annotation> annotation){ checkNotNull(object, "Precondition violation - argument 'object' must not be NULL!"); checkNotNull(annotation, "Precondition violation - argument 'annotation' must not be NULL!"); return getAnnotatedMethods(object.getClass(), annotation); } public static Set<Method> getAnnotatedMethods(final Class<?> clazz, final Class<? extends Annotation> annotation){ checkNotNull(clazz, "Precondition violation - argument 'clazz' must not be NULL!"); checkNotNull(annotation, "Precondition violation - argument 'annotation' must not be NULL!"); return getAllMethods(clazz).stream().filter(m -> m.isAnnotationPresent(annotation)).collect(Collectors.toSet()); } // ===================================================================================================================== // CONSTRUCTOR // ===================================================================================================================== private ReflectionUtils() { // do not instantiate } }
12,290
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
BasicAutoLock.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/autolock/BasicAutoLock.java
package org.chronos.common.autolock; import static com.google.common.base.Preconditions.*; import java.util.concurrent.locks.Lock; public class BasicAutoLock extends AbstractAutoLock { private final Lock lock; public BasicAutoLock(final Lock lock) { checkNotNull(lock, "Precondition violation - argument 'lock' must not be NULL!"); this.lock = lock; } @Override protected void doLock() { this.lock.lock(); } @Override protected void doUnlock() { this.lock.unlock(); } }
495
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AutoLock.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/autolock/AutoLock.java
package org.chronos.common.autolock; import static com.google.common.base.Preconditions.*; import java.util.concurrent.locks.Lock; /** * A {@link AutoLock} is an object that represents ownership over some sort of {@link Lock}. * * <p> * The basic idea here is to have a lock representation that implements {@link AutoCloseable} and can therefore work * with the <code>try-with-resources</code> statement. * * <p> * In general, a class making use of LockHolders should offer factory methods for the locks. These factories should * create a new lock holder (e.g. via {@link #createBasicLockHolderFor(Lock)}, then call {@link #acquireLock()} on it * before returning it. The caller can then use the following pattern: * * <pre> * try (LockHolder lock = theThingToBeLocked.lockFactoryMethod()) { * * // work in locked state here * * } // lock.close() is automatically invoked here, calling lock.release() * * </pre> * * * <p> * Please note that lock holder instances are always assumed to be <b>reusable</b> and <b>reentrant</b>. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public interface AutoLock extends AutoCloseable { /** * Creates a basic {@link AutoLock} instance that operates on the given {@link Lock}. * * @param lock * The lock to operate on. Must not be <code>null</code>. * * @return The newly created lock holder. Never <code>null</code>. */ public static AutoLock createBasicLockHolderFor(final Lock lock) { checkNotNull(lock, "Precondition violation - argument 'lock' must not be NULL!"); return new BasicAutoLock(lock); } /** * Releases the ownership of all locks represented by this object. * * <p> * All invocations after the first successful call to this method will be ignored and return immediately. */ @Override public default void close() { this.releaseLock(); } /** * Adds 1 to the internal lock counter. * * <p> * <b>Calling this method is usually not required.</b> It is recommended to stick to the default {@link AutoLock} * pattern using <code>try-with-resources</code> statements. * * @see #releaseLock() */ public void acquireLock(); /** * Subtracts 1 from the internal lock counter, unlocking the lock if the counter reaches zero. * * <p> * <b>Calling this method is usually not required.</b> It is recommended to stick to the default {@link AutoLock} * pattern using <code>try-with-resources</code> statements. * * @see #releaseLock() */ public void releaseLock(); }
2,548
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AbstractAutoLock.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/autolock/AbstractAutoLock.java
package org.chronos.common.autolock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class AbstractAutoLock implements AutoLock { private static final Logger log = LoggerFactory.getLogger(AbstractAutoLock.class); private int timesLockAcquired; protected AbstractAutoLock() { this.timesLockAcquired = 0; } @Override public final void acquireLock() { if (this.timesLockAcquired == 0) { this.doLock(); this.timesLockAcquired = 1; } else { this.timesLockAcquired++; } } @Override public final void releaseLock() { if (this.timesLockAcquired > 1) { this.timesLockAcquired--; } else if (this.timesLockAcquired == 1) { this.doUnlock(); this.timesLockAcquired = 0; } else { throw new IllegalStateException("Attempted to 'unlock' a LockHolder that was not 'lock'ed before!"); } } @Override protected void finalize() throws Throwable { super.finalize(); if (this.timesLockAcquired > 0) { log.warn("WARNING! Non-released lock is being GC'ed! Releasing it now."); this.close(); } } protected abstract void doLock(); protected abstract void doUnlock(); }
1,142
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AutoLockable.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/autolock/AutoLockable.java
package org.chronos.common.autolock; /** * A {@link AutoLockable} is any object that can be locked {@linkplain #lock() locked} or using the * <code>try-with-resources</code> pattern. * * <p> * See {@link #lock()} for example usages. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public interface AutoLockable { /** * Declares that a thread is about to perform an exclusive task that can not run in parallel with other tasks. * * <p> * All invocations of this method must adhere to the following usage pattern: * * <pre> * try (LockHolder lock = lockable.lock()) { * // ... perform tasks ... * } * </pre> * * This method ensures that exclusive operations are properly blocked when another operation is taking place. * * @return The object representing lock ownership. The lock ownership will be released once {@link AutoLock#close()} * is invoked, which is called automatically by the try-with-resources statement. */ public AutoLock lock(); }
1,028
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ReadWriteAutoLockable.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common/src/main/java/org/chronos/common/autolock/ReadWriteAutoLockable.java
package org.chronos.common.autolock; /** * A {@link ReadWriteAutoLockable} is any object that can be locked {@linkplain #lockExclusive() exclusively} or * {@linkplain #lockNonExclusive() non-exclusively} using the <code>try-with-resources</code> pattern. * * <p> * See {@link #lockExclusive()} and {@link #lockNonExclusive()} for example usages. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public interface ReadWriteAutoLockable { /** * Declares that a thread is about to perform an exclusive task that can not run in parallel with other tasks. * * <p> * All invocations of this method must adhere to the following usage pattern: * * <pre> * try (LockHolder lock = lockable.lockExclusive()) { * // ... perform tasks ... * } * </pre> * * This method ensures that exclusive operations are properly blocked when another operation is taking place. * * @return The object representing lock ownership. The lock ownership will be released once {@link AutoLock#close()} * is invoked, which is called automatically by the try-with-resources statement. */ 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. * * <p> * All invocations of this method must adhere to the following usage pattern: * * <pre> * try (LockHolder lock = lockable.lockNonExclusive()) { * // ... perform tasks ... * } * </pre> * * This method ensures that non-exclusive operations are properly blocked when an exclusive operation is taking * place. * * @return The object representing lock ownership. The lock ownership will be released once {@link AutoLock#close()} * is invoked, which is called automatically by the try-with-resources statement. */ public AutoLock lockNonExclusive(); }
1,904
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
PersonGeneratorTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common.testing/src/test/java/org/chronos/common/testing/test/cases/PersonGeneratorTest.java
package org.chronos.common.testing.test.cases; import org.chronos.common.test.utils.model.person.Person; import org.chronos.common.test.utils.model.person.PersonGenerator; import org.junit.Test; import static org.junit.Assert.*; public class PersonGeneratorTest { @Test public void canGeneratePerson(){ Person person = PersonGenerator.generateRandomPerson(); assertNotNull(person); assertNotNull(person.getFirstName()); assertNotNull(person.getLastName()); assertTrue(person.getFirstName().length() > 0); assertTrue(person.getLastName().length() > 0); } }
621
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronosTestWatcher.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common.testing/src/main/java/org/chronos/common/test/ChronosTestWatcher.java
package org.chronos.common.test; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import org.junit.AssumptionViolatedException; import org.junit.rules.TestWatcher; import org.junit.runner.Description; class ChronosTestWatcher extends TestWatcher { private Long startTime; @Override protected void starting(final Description description) { super.starting(description); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); this.startTime = date.getTime(); String startTime = dateFormat.format(date); StringBuilder msg = new StringBuilder(); msg.append("\n\n"); msg.append("================================================================================\n"); msg.append(" TEST START \n"); msg.append("--------------------------------------------------------------------------------\n"); msg.append(" Test class: " + description.getTestClass().getSimpleName() + "\n"); msg.append(" Test method: " + description.getMethodName() + "\n"); msg.append(" Start time: " + startTime + "\n"); msg.append("================================================================================\n"); msg.append("\n\n"); System.out.println(msg.toString()); } @Override protected void failed(final Throwable e, final Description description) { super.failed(e, description); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); long duration = date.getTime() - this.startTime; this.startTime = null; String endTime = dateFormat.format(date); StringBuilder msg = new StringBuilder(); msg.append("\n\n"); msg.append("================================================================================\n"); msg.append(" TEST FAILED \n"); msg.append("--------------------------------------------------------------------------------\n"); msg.append(" Test class: " + description.getTestClass().getSimpleName() + "\n"); msg.append(" Test method: " + description.getMethodName() + "\n"); msg.append(" End time: " + endTime + " (Duration: " + duration + "ms)\n"); msg.append("================================================================================\n"); msg.append("\n\n"); System.out.println(msg.toString()); } @Override protected void succeeded(final Description description) { super.succeeded(description); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); long duration = date.getTime() - this.startTime; this.startTime = null; String endTime = dateFormat.format(date); StringBuilder msg = new StringBuilder(); msg.append("\n\n"); msg.append("================================================================================\n"); msg.append(" TEST SUCCEEDED \n"); msg.append("--------------------------------------------------------------------------------\n"); msg.append(" Test class: " + description.getTestClass().getSimpleName() + "\n"); msg.append(" Test method: " + description.getMethodName() + "\n"); msg.append(" End time: " + endTime + " (Duration: " + duration + "ms)\n"); msg.append("================================================================================\n"); msg.append("\n\n"); System.out.println(msg.toString()); } @Override protected void skipped(final AssumptionViolatedException e, final Description description) { super.skipped(e, description); } }
3,675
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronosUnitTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common.testing/src/main/java/org/chronos/common/test/ChronosUnitTest.java
package org.chronos.common.test; import org.apache.commons.io.FileUtils; import org.chronos.common.util.ReflectionUtils; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.rules.TestName; import org.junit.rules.TestRule; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.util.UUID; import static com.google.common.base.Preconditions.*; import static org.junit.Assert.*; public abstract class ChronosUnitTest { private static final Logger log = LoggerFactory.getLogger(ChronosUnitTest.class); protected static File tempDir; // ================================================================================================================= // CLASS SETUP & CLEANUP // ================================================================================================================= static { // note: we use 'static' here instead of '@BeforeClass', because JUnit calls // methods annotated with '@Parameters' first. In case of ChronoDB tests, this // will result in db instances being produced BEFORE the temp dir is ready. By // declaring this code inside a static initializer, we ensure that it gets called // before the data for parameterized tests is constructed. try { Path tempDirPath = Files.createTempDirectory("ChronoDBTest"); tempDir = tempDirPath.toFile(); tempDir.mkdirs(); } catch (IOException e) { log.info("Failed to provide temp directory: " + e.toString()); } } @BeforeClass public static void beforeClass() { // note: we need to make sure again that the temp dir is created. // This is necessary in addition to the static initializer because when multipe // classes that inherit from this class are instantiated during a Test Suite, // then @AfterClass will delete it after the first test class has finished, so // all subsequent test classes won't have it, unless we recreate it here. tempDir.mkdirs(); log.info("Temp directory is provided at: " + tempDir.getAbsolutePath()); } @AfterClass public static void afterClass() { if (tempDir != null && tempDir.exists()) { log.info("Attempting to delete temp directory provided at: " + tempDir.getAbsolutePath()); try { FileUtils.deleteDirectory(tempDir); log.info("Successfully deleted temp directory"); } catch (IOException e) { log.warn("Failed to delete temp directory: " + e.toString()); } } } // ================================================================================================================= // FIELDS // ================================================================================================================= private File testDirectory; @Rule public TestRule watcher = new ChronosTestWatcher(); @Rule public TestName testName = new TestName(); // ================================================================================================================= // TEST METHOD SETUP & CLEANUP // ================================================================================================================= @Before public void setup() { this.deleteTestDirectory(); String testDirName = "TestDirectory" + UUID.randomUUID().toString().replaceAll("-", ""); this.testDirectory = new File(tempDir, testDirName); this.testDirectory.mkdir(); } @After public void tearDown() { this.deleteTestDirectory(); } private void deleteTestDirectory() { if (this.testDirectory == null) { return; } if (this.testDirectory.exists() == false) { this.testDirectory = null; return; } try { FileUtils.deleteDirectory(this.testDirectory); } catch (IOException e) { log.warn("Failed to delete the test directory!"); } } protected File getTestDirectory() { return this.testDirectory; } protected Method getCurrentTestMethod() { String methodName = this.testName.getMethodName(); if (methodName == null) { return null; } // strip away the trailing "[case]" added by JUnit for parameterized tests (if any) methodName = methodName.replaceAll("\\[.*\\]", ""); return ReflectionUtils.getDeclaredMethod(this.getClass(), methodName); } // ================================================================================================================= // UTILITY METHODS // ================================================================================================================= protected static void sleep(final long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { log.error("Thread interrupted while sleeping!", e); } } protected File getSrcTestResourcesFile(final String fileName) { checkNotNull(fileName, "Precondition violation - argument 'fileName' must not be NULL!"); URL url = this.getClass().getResource("/" + fileName); File file; try { file = new File(url.toURI()); return file; } catch (URISyntaxException e) { fail(e.toString()); return null; } } }
5,815
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
TimeStatistics.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common.testing/src/main/java/org/chronos/common/test/utils/TimeStatistics.java
package org.chronos.common.test.utils; import java.util.List; import java.util.NoSuchElementException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TimeStatistics { private static final Logger log = LoggerFactory.getLogger(TimeStatistics.class); private final Statistic statistics; private Long currentRunStartTime; public TimeStatistics() { this.statistics = new Statistic(); } public TimeStatistics(final Statistic statistic) { this.statistics = statistic; } public void beginRun() { if (this.currentRunStartTime != null) { throw new IllegalStateException("A run is already going on!"); } this.currentRunStartTime = System.nanoTime(); } public long endRun() { long runEndTime = System.nanoTime(); if (this.currentRunStartTime == null) { throw new IllegalArgumentException("There is no run to end!"); } // convert nanoseconds to milliseconds long runtime = (runEndTime - this.currentRunStartTime) / 1_000_000; this.currentRunStartTime = null; this.statistics.addSample(runtime); return runtime; } public double getAverageRuntime() { return this.statistics.getAverage(); } public double getVariance() { return this.statistics.getVariance(); } public double getStandardDeviation() { return this.statistics.getStandardDeviation(); } public long getTotalTime() { return Math.round(this.statistics.getSum()); } public int getNumberOfRuns() { return this.statistics.getSampleSize(); } public long getLongestRuntime() { return Math.round(this.statistics.getMax()); } public long getShortestRuntime() { return Math.round(this.statistics.getMin()); } public long getQ1() throws NoSuchElementException { return Math.round(this.statistics.getQ1()); } public long getMedian() { return Math.round(this.statistics.getMedian()); } public long getQ2() { return Math.round(this.statistics.getQ2()); } public long getQ3() { return Math.round(this.statistics.getQ3()); } public List<Double> getRuntimes() { return this.statistics.getSamples(); } public String toFullString() { StringBuilder builder = new StringBuilder(); builder.append("TimeStatistics["); builder.append("Runs: "); builder.append(this.getNumberOfRuns()); builder.append(", "); builder.append("Total Time: "); builder.append(this.getTotalTime()); builder.append("ms, "); builder.append("Shortest Time: "); builder.append(this.getShortestRuntime()); builder.append("ms, "); builder.append("Longest Time: "); builder.append(this.getLongestRuntime()); builder.append("ms, "); builder.append("Average Time: "); builder.append(String.format("%1.3f", this.getAverageRuntime())); builder.append("ms, "); builder.append("Variance: "); builder.append(String.format("%1.3f", this.getVariance())); builder.append("ms, "); builder.append("Standard Deviation: "); builder.append(String.format("%1.3f", this.getStandardDeviation())); builder.append("ms, "); builder.append("Q1: "); builder.append(this.getQ1()); builder.append("ms, "); builder.append("Q2 (median): "); builder.append(this.getQ2()); builder.append("ms, "); builder.append("Q3: "); builder.append(this.getQ3()); builder.append("ms "); builder.append("]"); return builder.toString(); } public String toCSV() { StringBuilder builder = new StringBuilder(); builder.append("TimeStatistics["); builder.append("Runs;"); builder.append("Total Time (ms);"); builder.append("Shortest Time (ms); "); builder.append("Longest Time (ms); "); builder.append("Average Time (ms); "); builder.append("Variance (ms); "); builder.append("Standard Deviation (ms); "); builder.append("Q1 (ms); "); builder.append("Q2 (median) (ms); "); builder.append("Q3 (ms); "); builder.append(" ;; "); builder.append(this.getNumberOfRuns()); builder.append("; "); builder.append(this.getTotalTime()); builder.append("; "); builder.append(this.getShortestRuntime()); builder.append("; "); builder.append(this.getLongestRuntime()); builder.append("; "); builder.append(String.format("%1.3f", this.getAverageRuntime())); builder.append("; "); builder.append(String.format("%1.3f", this.getVariance())); builder.append("; "); builder.append(String.format("%1.3f", this.getStandardDeviation())); builder.append("; "); builder.append(this.getQ1()); builder.append("; "); builder.append(this.getQ2()); builder.append("; "); builder.append(this.getQ3()); builder.append("; "); builder.append("]"); return builder.toString(); } public void log() { log.info(this.toFullString()); } }
4,627
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
NamedPayload.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common.testing/src/main/java/org/chronos/common/test/utils/NamedPayload.java
package org.chronos.common.test.utils; import com.google.common.collect.Sets; import org.apache.commons.io.FileUtils; import java.io.Serializable; import java.util.Arrays; import java.util.Random; import java.util.Set; import java.util.UUID; import static com.google.common.base.Preconditions.*; /** * A class for testing purposes. * * <p> * Instances of this class are supposed to be used as values for the temporal key-value store. This class provides: * * <ul> * <li>A {@link #name} (not <code>null</code>), to be used for identification purposes * <li>A {@link #payload} (not <code>null</code>), to simulate the size of a real-world value object * </ul> * <p> * Note that this class has several factory methods for easier access. Instances of this class are considered to be * immutable. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API */ public class NamedPayload implements Serializable { // ================================================================================================================= // SERIAL VERSION ID // ================================================================================================================= private static final long serialVersionUID = 1L; // ================================================================================================================= // STATIC FACTORY METHODS // ================================================================================================================= /** * Factory method. Creates a new {@link NamedPayload} with a random UUID as {@link #name} and a random 1KB * {@link #payload}. * * <p> * <b>Disclaimer:</b> It is only guaranteed that the {@link #payload} has the specified size. The total size of the * returned object as a whole will be larger, due to the memory consumed by the {@link #name} and the overhead of * the JVM. In particular, keep in mind that serialized forms of this class may be subject to compression algorithms * and have different sizes. * * @return The newly created {@link NamedPayload} object. */ public static NamedPayload create1KB() { return createKB(1); } /** * Factory method. Creates a new {@link NamedPayload} with the given {@link #name} and a random 1KB {@link #payload} * . * * <p> * <b>Disclaimer:</b> It is only guaranteed that the {@link #payload} has the specified size. The total size of the * returned object as a whole will be larger, due to the memory consumed by the {@link #name} and the overhead of * the JVM. In particular, keep in mind that serialized forms of this class may be subject to compression algorithms * and have different sizes. * * @param name The name to assign to the new object. Must not be <code>null</code>. * @return The newly created {@link NamedPayload} object. */ public static NamedPayload create1KB(final String name) { checkNotNull(name, "Precondition violation - argument 'name' must not be NULL!"); return createKB(name, 1); } /** * Factory method. Creates a new {@link NamedPayload} with a random UUID as {@link #name} and a random 10KB * {@link #payload}. * * <p> * <b>Disclaimer:</b> It is only guaranteed that the {@link #payload} has the specified size. The total size of the * returned object as a whole will be larger, due to the memory consumed by the {@link #name} and the overhead of * the JVM. In particular, keep in mind that serialized forms of this class may be subject to compression algorithms * and have different sizes. * * @return The newly created {@link NamedPayload} object. */ public static NamedPayload create10KB() { return createKB(10); } /** * Factory method. Creates a new {@link NamedPayload} with the given {@link #name} and a random 10KB * {@link #payload} . * * <p> * <b>Disclaimer:</b> It is only guaranteed that the {@link #payload} has the specified size. The total size of the * returned object as a whole will be larger, due to the memory consumed by the {@link #name} and the overhead of * the JVM. In particular, keep in mind that serialized forms of this class may be subject to compression algorithms * and have different sizes. * * @param name The name to assign to the new object. Must not be <code>null</code>. * @return The newly created {@link NamedPayload} object. */ public static NamedPayload create10KB(final String name) { checkNotNull(name, "Precondition violation - argument 'name' must not be NULL!"); return createKB(name, 10); } /** * Factory method. Creates a new {@link NamedPayload} with a random UUID as {@link #name} and a random 100KB * {@link #payload}. * * <p> * <b>Disclaimer:</b> It is only guaranteed that the {@link #payload} has the specified size. The total size of the * returned object as a whole will be larger, due to the memory consumed by the {@link #name} and the overhead of * the JVM. In particular, keep in mind that serialized forms of this class may be subject to compression algorithms * and have different sizes. * * @return The newly created {@link NamedPayload} object. */ public static NamedPayload create100KB() { return createKB(100); } /** * Factory method. Creates a new {@link NamedPayload} with the given {@link #name} and a random 100KB * {@link #payload} . * * <p> * <b>Disclaimer:</b> It is only guaranteed that the {@link #payload} has the specified size. The total size of the * returned object as a whole will be larger, due to the memory consumed by the {@link #name} and the overhead of * the JVM. In particular, keep in mind that serialized forms of this class may be subject to compression algorithms * and have different sizes. * * @param name The name to assign to the new object. Must not be <code>null</code>. * @return The newly created {@link NamedPayload} object. */ public static NamedPayload create100KB(final String name) { checkNotNull(name, "Precondition violation - argument 'name' must not be NULL!"); return createKB(name, 100); } /** * Factory method. Creates a new {@link NamedPayload} with a random UUID as {@link #name} and a random 1MB * {@link #payload}. * * <p> * <b>Disclaimer:</b> It is only guaranteed that the {@link #payload} has the specified size. The total size of the * returned object as a whole will be larger, due to the memory consumed by the {@link #name} and the overhead of * the JVM. In particular, keep in mind that serialized forms of this class may be subject to compression algorithms * and have different sizes. * * @return The newly created {@link NamedPayload} object. */ public static NamedPayload create1MB() { return createMB(1); } /** * Factory method. Creates a new {@link NamedPayload} with the given {@link #name} and a random 1MB {@link #payload} * . * * <p> * <b>Disclaimer:</b> It is only guaranteed that the {@link #payload} has the specified size. The total size of the * returned object as a whole will be larger, due to the memory consumed by the {@link #name} and the overhead of * the JVM. In particular, keep in mind that serialized forms of this class may be subject to compression algorithms * and have different sizes. * * @param name The name to assign to the new object. Must not be <code>null</code>. * @return The newly created {@link NamedPayload} object. */ public static NamedPayload create1MB(final String name) { checkNotNull(name, "Precondition violation - argument 'name' must not be NULL!"); return createMB(name, 1); } /** * Factory method. Creates a new {@link NamedPayload} with a random UUID as {@link #name} and a random * {@link #payload} of the specified size. * * <p> * <b>Disclaimer:</b> It is only guaranteed that the {@link #payload} has the specified size. The total size of the * returned object as a whole will be larger, due to the memory consumed by the {@link #name} and the overhead of * the JVM. In particular, keep in mind that serialized forms of this class may be subject to compression algorithms * and have different sizes. * * @param payloadKiloBytes The size of the intended payload, in kilobytes (KB). Must not be negative. * @return The newly created {@link NamedPayload} object. */ public static NamedPayload createKB(final int payloadKiloBytes) { return createKB(UUID.randomUUID().toString(), payloadKiloBytes); } /** * Factory method. Creates a new {@link NamedPayload} with the given {@link #name} and a random {@link #payload} of * the specified size. * * <p> * <b>Disclaimer:</b> It is only guaranteed that the {@link #payload} has the specified size. The total size of the * returned object as a whole will be larger, due to the memory consumed by the {@link #name} and the overhead of * the JVM. In particular, keep in mind that serialized forms of this class may be subject to compression algorithms * and have different sizes. * * @param name The name to assign to the new object. Must not be <code>null</code>. * @param payloadKiloBytes The size of the intended payload, in kilobytes (KB). Must not be negative. * @return The newly created {@link NamedPayload} object. */ public static NamedPayload createKB(final String name, final int payloadKiloBytes) { checkNotNull(name, "Precondition violation - argument 'name' must not be NULL!"); checkArgument(payloadKiloBytes >= 0, "Precondition violation - argument 'payloadKiloBytes' (value: " + payloadKiloBytes + ") must be >= 0!"); return new NamedPayload(name, payloadKiloBytes * 1024); } /** * Factory method. Creates a new {@link NamedPayload} with a random UUID as {@link #name} and a random * {@link #payload} of the specified size. * * <p> * <b>Disclaimer:</b> It is only guaranteed that the {@link #payload} has the specified size. The total size of the * returned object as a whole will be larger, due to the memory consumed by the {@link #name} and the overhead of * the JVM. In particular, keep in mind that serialized forms of this class may be subject to compression algorithms * and have different sizes. * * @param payloadMegaBytes The size of the intended payload, in megabytes (MB). Must not be negative. * @return The newly created {@link NamedPayload} object. */ public static NamedPayload createMB(final int payloadMegaBytes) { return createKB(UUID.randomUUID().toString(), payloadMegaBytes); } /** * Factory method. Creates a new {@link NamedPayload} with the given {@link #name} and a random {@link #payload} of * the specified size. * * <p> * <b>Disclaimer:</b> It is only guaranteed that the {@link #payload} has the specified size. The total size of the * returned object as a whole will be larger, due to the memory consumed by the {@link #name} and the overhead of * the JVM. In particular, keep in mind that serialized forms of this class may be subject to compression algorithms * and have different sizes. * * @param name The name to assign to the new object. Must not be <code>null</code>. * @param payloadMegaBytes The size of the intended payload, in megabytes (MB). Must not be negative. * @return The newly created {@link NamedPayload} object. */ public static NamedPayload createMB(final String name, final int payloadMegaBytes) { checkNotNull(name, "Precondition violation - argument 'name' must not be NULL!"); checkArgument(payloadMegaBytes >= 0, "Precondition violation - argument 'payloadMegaBytes' (value: " + payloadMegaBytes + ") must be >= 0!"); return new NamedPayload(name, payloadMegaBytes * 1024 * 1024); } /** * Creates the given number of {@link NamedPayload} instances. * * <p> * Each instance will have a random {@link UUID} as name and a random payload of the given size. * * @param numberOfInstances The number of instances to create. Must be greater than zero. * @param payloadKiloBytes The size of the payload for each instance, in kilobytes (KB). Must not be negative. * @return The set of created instances. */ public static Set<NamedPayload> createMany(final int numberOfInstances, final int payloadKiloBytes) { checkArgument(numberOfInstances > 0, "Precondition violation - argument 'numberOfInstances' (value: " + numberOfInstances + ") must be > 0!"); checkArgument(payloadKiloBytes >= 0, "Precondition violation - argument 'payloadKiloBytes' (value: " + payloadKiloBytes + ") must be >= 0!"); Set<NamedPayload> resultSet = Sets.newHashSet(); for (int i = 0; i < numberOfInstances; i++) { NamedPayload instance = createKB(payloadKiloBytes); resultSet.add(instance); } return resultSet; } // ================================================================================================================= // PROPERTIES // ================================================================================================================= /** * The name of this object. Never <code>null</code>. */ private String name; /** * The actual payload data contained in this object. */ private byte[] payload; // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= protected NamedPayload() { // default constructor for serialization purposes } /** * Creates a new {@link NamedPayload} instance with the given parameters. * * <p> * Please use one of the factory methods provided by this class instead for better readability. * * @param name The name of the new object. Must not be <code>null</code>. * @param payloadSizeBytes The intended size of the payload, in Bytes. Must not be negative. */ protected NamedPayload(final String name, final int payloadSizeBytes) { checkNotNull(name, "Precondition violation - argument 'name' must not be NULL!"); checkArgument(payloadSizeBytes >= 0, "Precondition violation - argument 'payloadSizeBytes' (value: " + payloadSizeBytes + ") must be >= 0!"); this.name = name; this.payload = new byte[payloadSizeBytes]; new Random().nextBytes(this.payload); } // ================================================================================================================= // GETTERS & SETTERS // ================================================================================================================= /** * Returns the size of the contained payload in Bytes. * * @return The size of the containd payload in Bytes. */ public int getPayloadSizeInBytes() { return this.payload.length; } /** * Returns a copy of the internal payload array. * * @return A copy of the internal payload array. Never <code>null</code>. Modifications on the returned array will * not modify the internal state of this object. */ public byte[] getPayload() { byte[] result = new byte[this.getPayloadSizeInBytes()]; System.arraycopy(this.payload, 0, result, 0, this.getPayloadSizeInBytes()); return result; } /** * Returns the name of this object. * * @return The name of this object. Never <code>null</code>. */ public String getName() { return this.name; } // ===================================================================================================================== // HASH CODE & EQUALS // ===================================================================================================================== @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.name == null ? 0 : this.name.hashCode()); result = prime * result + Arrays.hashCode(this.payload); 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; } NamedPayload other = (NamedPayload) obj; if (this.name == null) { if (other.name != null) { return false; } } else if (!this.name.equals(other.name)) { return false; } if (!Arrays.equals(this.payload, other.payload)) { return false; } return true; } // ================================================================================================================= // TO STRING // ================================================================================================================= @Override public String toString() { return "NamedPayload['" + this.getName() + "', " + FileUtils.byteCountToDisplaySize(this.payload.length) + "]"; } }
17,960
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
Measure.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common.testing/src/main/java/org/chronos/common/test/utils/Measure.java
package org.chronos.common.test.utils; import java.util.Map; import java.util.function.Consumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Maps; public class Measure { private static final Logger log = LoggerFactory.getLogger(Measure.class); private static final Map<String, Long> idToStartTime = Maps.newHashMap(); public static void startTimeMeasure(final String id) { if (id == null) { throw new IllegalArgumentException("Precondition violation - argument 'id' must not be NULL!"); } long startTime = System.nanoTime(); idToStartTime.put(id, startTime); } public static long endTimeMeasure(final String id) { long endTime = System.nanoTime(); if (id == null) { throw new IllegalArgumentException("Precondition violation - argument 'id' must not be NULL!"); } Long startTime = idToStartTime.remove(id); if (startTime == null) { throw new IllegalStateException("A timer for '" + id + "' does not exist!"); } long runtime = (endTime - startTime) / 1000000; log.debug("Time for action [" + id + "]: " + runtime + "ms."); return runtime; } public static TimeStatistics multipleTimes(final int times, final boolean writeLog, final Runnable task) { TimeStatistics statistics = new TimeStatistics(); for (int run = 0; run < times; run++) { statistics.beginRun(); task.run(); statistics.endRun(); } if (writeLog) { statistics.log(); } return statistics; } public static TimeStatistics multipleTimes(final int times, final boolean writeLog, final Consumer<Integer> task) { TimeStatistics statistics = new TimeStatistics(); for (int run = 0; run < times; run++) { statistics.beginRun(); task.accept(run); statistics.endRun(); } if (writeLog) { statistics.log(); } return statistics; } }
1,831
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
TestUtils.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common.testing/src/main/java/org/chronos/common/test/utils/TestUtils.java
package org.chronos.common.test.utils; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import java.lang.reflect.Array; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import java.util.Collection; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; import java.util.UUID; import java.util.function.Supplier; import static com.google.common.base.Preconditions.*; public class TestUtils { @SuppressWarnings("unchecked") public static <T> T createProxy(final Class<T> theInterface, final InvocationHandler handler) { checkNotNull(theInterface, "Precondition violation - argument 'theInterface' must not be NULL!"); checkNotNull(handler, "Precondition violation - argument 'handler' must not be NULL!"); checkArgument(theInterface.isInterface(), "Precondition violation - argument 'theInterface' must be an interface, not a class!"); Class<T>[] classes = (Class<T>[]) Array.newInstance(Class.class, 1); classes[0] = theInterface; return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), classes, handler); } public static Set<String> randomKeySet(final long size) { Set<String> keySet = Sets.newHashSet(); for (int i = 0; i < size; i++) { keySet.add(UUID.randomUUID().toString()); } return keySet; } public static List<String> randomKeySetAsList(final long size) { List<String> keys = Lists.newArrayList(); for (int i = 0; i < size; i++) { keys.add(UUID.randomUUID().toString()); } return keys; } public static int randomBetween(final int lower, final int upper) { if (lower > upper) { throw new IllegalArgumentException("lower > upper: " + lower + " > " + upper); } if (lower == upper) { return lower; } double random = Math.random(); return (int) (lower + Math.round((upper - lower) * random)); } public static long randomBetween(final long lower, final long upper) { if (lower > upper) { throw new IllegalArgumentException("lower > upper: " + lower + " > " + upper); } if (lower == upper) { return lower; } double random = Math.random(); return lower + Math.round((upper - lower) * random); } public static double lerp(final double lower, final double upper, final double percent) { return lower + percent * (upper - lower); } public static <T> List<T> generateValuesList(final Supplier<T> factory, final int size) { return generateValues(factory, Lists.newArrayList(), size); } public static <T> Set<T> generateValuesSet(final Supplier<T> factory, final int size) { return generateValues(factory, Sets.newHashSet(), size); } public static <T, C extends Collection<T>> C generateValues(final Supplier<T> factory, final C collection, final int size) { for (int i = 0; i < size; i++) { T element = factory.get(); collection.add(element); } return collection; } public static <T> T getRandomEntryOf(final List<T> list) { if (list == null) { throw new NullPointerException("Precondition violation - argument 'list' must not be NULL!"); } if (list.isEmpty()) { throw new NoSuchElementException("List is empty, cannot get random entry!"); } int index = randomBetween(0, list.size() - 1); return list.get(index); } public static <T> Set<T> getRandomUniqueEntriesOf(final List<T> list, final int entries) { checkNotNull(list, "Precondition violation - argument 'list' must not be NULL!"); checkArgument(entries >= 0, "Precondition violation - argument 'entries' must not be negative!"); checkArgument(entries <= list.size(), "Precondition violation - argument 'entries' must not exceed the list size!"); Set<T> resultSet = Sets.newHashSet(); for (int i = 0; i < entries; i++) { boolean added = false; while (!added) { T entry = getRandomEntryOf(list); added = resultSet.add(entry); } } return resultSet; } }
4,374
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
Statistic.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common.testing/src/main/java/org/chronos/common/test/utils/Statistic.java
package org.chronos.common.test.utils; import static com.google.common.base.Preconditions.*; import java.util.Collections; import java.util.List; import java.util.NoSuchElementException; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import com.google.common.collect.Lists; /** * This is a thread-safe list of statistic samples that is capable of providing standard statistic information. * * <p> * The "samples" are stored as <code>double</code> values. The meaning of each sample is decided by the application that uses this class. Please note that this class is intended only for samples which are greater than zero. * * <p> * This class is completely thread-safe. All operations internally make use of a {@link ReadWriteLock} for synchronization. * * <p> * Instances of this class can be created using the constructor. No additional handling is required. * * <p> * Usage example: * * <pre> * Statistics statistics = new Statistics(); * statistics.addSample(123); * statistics.addSample(456); * // ... add more ... * * // retrieve the statistic information * double average = statistics.getAverage(); * double variance = statistics.getVariance(); * double standardDeviation = statistics.getStandardDeviation(); * </pre> * * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public class Statistic { // ================================================================================================================= // FIELDS // ================================================================================================================= /** The read-write lock used for access synchronization on the samples */ private ReadWriteLock lock = new ReentrantReadWriteLock(true); /** The list of samples. A plain list data structure without special features. */ private List<Double> samples = Lists.newArrayList(); // ================================================================================================================= // PUBLIC API // ================================================================================================================= /** * Adds the given sample to this statistic. * * @param sample * The sample to add. Must be greater than zero. */ public void addSample(final double sample) { checkArgument(sample >= 0, "Precondition violation - argument 'sample' must be >= 0 (value: " + sample + ")!"); this.lock.writeLock().lock(); try { this.samples.add(sample); } finally { this.lock.writeLock().unlock(); } } /** * Returns an immutable list containing the current samples. * * @return An immutable list with the current samples. May be empty, but never <code>null</code>. */ public List<Double> getSamples() { this.lock.readLock().lock(); try { List<Double> resultList = Lists.newArrayList(this.samples); return Collections.unmodifiableList(resultList); } finally { this.lock.readLock().unlock(); } } /** * Returns the average of all samples. * * @return The average value. */ public double getAverage() { this.lock.readLock().lock(); try { double sum = this.getSum(); int sampleSize = this.getSampleSize(); return sum / sampleSize; } finally { this.lock.readLock().unlock(); } } /** * Returns the variance of all samples. * * @return The variance. */ public double getVariance() { this.lock.readLock().lock(); try { double avg = this.getAverage(); int sampleSize = this.getSampleSize(); double variance = this.samples.parallelStream().mapToDouble(time -> Math.pow(time - avg, 2)).sum() / sampleSize; return variance; } finally { this.lock.readLock().unlock(); } } /** * Returns the standard deviation of all samples. * * @return The standard deviation. */ public double getStandardDeviation() { this.lock.readLock().lock(); try { return Math.sqrt(this.getVariance()); } finally { this.lock.readLock().unlock(); } } /** * Returns the sum of all samples. * * @return The sum. */ public double getSum() { this.lock.readLock().lock(); try { return this.samples.parallelStream().mapToDouble(l -> l).sum(); } finally { this.lock.readLock().unlock(); } } /** * Returns the sample size, i.e. the number of samples in this statistic. * * @return The sample size. */ public int getSampleSize() { this.lock.readLock().lock(); try { return this.samples.size(); } finally { this.lock.readLock().unlock(); } } /** * Returns the largest sample in this statistic. * * @return The largest sample. * * @throws NoSuchElementException * Thrown if this statistic is empty and therefore has no maximum sample. */ public double getMax() throws NoSuchElementException { this.assertNotEmpty(); this.lock.readLock().lock(); try { return this.samples.stream().mapToDouble(v -> v).max().getAsDouble(); } finally { this.lock.readLock().unlock(); } } /** * Returns the smallest sample in this statistic. * * @return The smallest sample. * * @throws NoSuchElementException * Thrown if this statistic is empty and therefore has no minimum sample. */ public double getMin() throws NoSuchElementException { this.assertNotEmpty(); this.lock.readLock().lock(); try { return this.samples.stream().mapToDouble(v -> v).min().getAsDouble(); } finally { this.lock.readLock().unlock(); } } /** * Checks if this statistic is empty, i.e. contains no samples. * * @return <code>true</code> if this statistic has no samples, <code>false</code> if there is at least one sample. */ public boolean isEmpty() { this.lock.readLock().lock(); try { return this.samples.isEmpty(); } finally { this.lock.readLock().unlock(); } } /** * Gets the first quartile of the statistic. * * @return The first quartile. * * @throws NoSuchElementException * Thrown if this statistic is empty and therefore has no first quartile. */ public double getQ1() throws NoSuchElementException { this.assertNotEmpty(); return this.getPercentile(25); } /** * Gets the median (second quartile) of the statistic. * * @return The median. * * @throws NoSuchElementException * Thrown if this statistic is empty and therefore has no median. */ public double getMedian() { this.assertNotEmpty(); return this.getQ2(); } /** * Gets the second quartile of the statistic. * * @return The second quartile. * * @throws NoSuchElementException * Thrown if this statistic is empty and therefore has no second quartile. */ public double getQ2() { this.assertNotEmpty(); return this.getPercentile(50); } /** * Gets the third quartile of the statistic. * * @return The third quartile. * * @throws NoSuchElementException * Thrown if this statistic is empty and therefore has no third quartile. */ public double getQ3() { this.assertNotEmpty(); return this.getPercentile(75); } private double getPercentile(final double percent) { this.lock.readLock().lock(); try { List<Double> sorted = Lists.newArrayList(this.samples); Collections.sort(sorted); int index = (int) Math.round(sorted.size() * percent / 100); index = Math.min(index, sorted.size() - 1); return sorted.get(index); } finally { this.lock.readLock().unlock(); } } private void assertNotEmpty() { if (this.isEmpty()) { throw new NoSuchElementException("Statistic contains no data points!"); } } }
7,645
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
Person.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.common.testing/src/main/java/org/chronos/common/test/utils/model/person/Person.java
package org.chronos.common.test.utils.model.person; import com.google.common.collect.Sets; import java.util.List; import java.util.Set; import java.util.UUID; public class Person { // ===================================================================================================================== // STATIC METHODS // ===================================================================================================================== public static Person generateRandom() { return PersonGenerator.generateRandomPerson(); } public static List<Person> generateRandom(final int setSize) { return PersonGenerator.generateRandomPersons(setSize); } // ===================================================================================================================== // FIELDS // ===================================================================================================================== private String id; private String firstName; private String lastName; private String favoriteColor; private Set<String> hobbies; private Set<String> pets; // ===================================================================================================================== // CONSTRUCTOR // ===================================================================================================================== public Person() { this.id = UUID.randomUUID().toString(); this.hobbies = Sets.newHashSet(); this.pets = Sets.newHashSet(); } public Person(final String firstName, final String lastName) { this(); this.setFirstName(firstName); this.setLastName(lastName); } public Person(final String id, final String firstName, final String lastName) { this(); this.id = id; this.setFirstName(firstName); this.setLastName(lastName); } // ===================================================================================================================== // PUBLIC API // ===================================================================================================================== public String getId() { return this.id; } public String getFirstName() { return this.firstName; } public void setFirstName(final String firstName) { this.firstName = firstName; } public String getLastName() { return this.lastName; } public void setLastName(final String lastName) { this.lastName = lastName; } public String getFavoriteColor() { return this.favoriteColor; } public void setFavoriteColor(final String favoriteColor) { this.favoriteColor = favoriteColor; } public Set<String> getHobbies() { return this.hobbies; } public void setHobbies(final Set<String> hobbies) { this.hobbies = Sets.newHashSet(hobbies); } public void setHobbies(final String... hobbies) { this.hobbies = Sets.newHashSet(hobbies); } public Set<String> getPets() { return this.pets; } public void setPets(final Set<String> pets) { this.pets = Sets.newHashSet(pets); } public void setPets(final String... pets) { this.pets = Sets.newHashSet(pets); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.id == null ? 0 : this.id.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; } Person other = (Person) obj; if (this.id == null) { if (other.id != null) { return false; } } else if (!this.id.equals(other.id)) { return false; } return true; } public boolean contentEquals(final Person obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } Person other = obj; if (this.favoriteColor == null) { if (other.favoriteColor != null) { return false; } } else if (!this.favoriteColor.equals(other.favoriteColor)) { return false; } if (this.firstName == null) { if (other.firstName != null) { return false; } } else if (!this.firstName.equals(other.firstName)) { return false; } if (this.hobbies == null) { if (other.hobbies != null) { return false; } } else if (!this.hobbies.equals(other.hobbies)) { return false; } if (this.id == null) { if (other.id != null) { return false; } } else if (!this.id.equals(other.id)) { return false; } if (this.lastName == null) { if (other.lastName != null) { return false; } } else if (!this.lastName.equals(other.lastName)) { return false; } if (this.pets == null) { if (other.pets != null) { return false; } } else if (!this.pets.equals(other.pets)) { return false; } return true; } @Override public String toString() { return "P['" + this.firstName + "' '" + this.lastName + "']"; } }
5,833
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z