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
ChronoDBUnitTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/base/ChronoDBUnitTest.java
package org.chronos.chronodb.test.base; import org.chronos.chronodb.api.Branch; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.internal.api.BranchInternal; import org.chronos.chronodb.internal.api.TemporalKeyValueStore; import org.chronos.common.test.ChronosUnitTest; public class ChronoDBUnitTest extends ChronosUnitTest { protected TemporalKeyValueStore getMasterTkvs(final ChronoDB db) { return this.getTkvs(db, ChronoDBConstants.MASTER_BRANCH_IDENTIFIER); } protected TemporalKeyValueStore getTkvs(final ChronoDB db, final String branchName) { Branch branch = db.getBranchManager().getBranch(branchName); return ((BranchInternal) branch).getTemporalKeyValueStore(); } }
763
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AllChronoDBBackendsTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/base/AllChronoDBBackendsTest.java
package org.chronos.chronodb.test.base; import com.google.common.collect.Lists; import org.apache.commons.configuration2.Configuration; import org.chronos.chronodb.api.Branch; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.builder.database.ChronoDBPropertyFileBuilder; import org.chronos.chronodb.api.builder.query.FinalizableQueryBuilder; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.internal.api.BranchInternal; import org.chronos.chronodb.internal.api.ChronoDBConfiguration; import org.chronos.chronodb.internal.api.TemporalKeyValueStore; import org.junit.After; import org.junit.Assume; 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.stream.Collectors; import static com.google.common.base.Preconditions.*; import static org.junit.Assert.*; public abstract class AllChronoDBBackendsTest extends AllBackendsTest { private static final Logger log = LoggerFactory.getLogger(AllChronoDBBackendsTest.class); // ================================================================================================================= // FIELDS // ================================================================================================================= private ChronoDB db; // ================================================================================================================= // GETTERS & SETTERS // ================================================================================================================= protected ChronoDB getChronoDB() { if (this.db == null) { this.db = this.instantiateChronoDB(this.backend); } return this.db; } // ================================================================================================================= // JUNIT CONTROL // ================================================================================================================= @After public void cleanUp() { log.debug("Closing ChronoDB on backend '" + this.backend + "'."); if (this.db != null) { if (this.db.isClosed() == false) { this.db.close(); } this.db = null; } } // ================================================================================================================= // UTILITY // ================================================================================================================= protected ChronoDB instantiateChronoDB(final String backend) { return this.instantiateChronoDB(backend, Collections.emptyMap()); } protected ChronoDB instantiateChronoDB(final String backend, Map<String, Object> additionalConfiguration) { Configuration configuration = this.createChronosConfiguration(backend); for(Entry<String, Object> entry : additionalConfiguration.entrySet()){ configuration.setProperty(entry.getKey(), entry.getValue()); } return this.createDB(configuration); } protected ChronoDB createDB(final Configuration configuration) { checkNotNull(configuration, "Precondition violation - argument 'configuration' must not be NULL!"); ChronoDBPropertyFileBuilder builder = ChronoDB.FACTORY.create().fromConfiguration(configuration); this.applyExtraTestMethodProperties(configuration); return builder.build(); } protected ChronoDB reinstantiateDB() { return this.reinstantiateDB(Collections.emptyMap()); } protected ChronoDB reinstantiateDB(Map<String, Object> additionalConfiguration) { log.debug("Reinstantiating ChronoDB on backend '" + this.backend + "'."); if (this.db != null) { this.db.close(); } this.db = this.instantiateChronoDB(this.backend, additionalConfiguration); return this.db; } protected ChronoDB closeAndReopenDB() { ChronoDB db = this.getChronoDB(); // this won't work for in-memory (obviously) Assume.assumeTrue(db.getFeatures().isPersistent()); ChronoDBConfiguration configuration = db.getConfiguration(); db.close(); this.db = ChronoDB.FACTORY.create().fromConfiguration(configuration.asCommonsConfiguration()).build(); return this.db; } protected TemporalKeyValueStore getMasterTkvs(final ChronoDB db) { return this.getTkvs(db, ChronoDBConstants.MASTER_BRANCH_IDENTIFIER); } protected TemporalKeyValueStore getTkvs(final ChronoDB db, final String branchName) { Branch branch = db.getBranchManager().getBranch(branchName); return ((BranchInternal) branch).getTemporalKeyValueStore(); } protected void assumeRolloverIsSupported(final ChronoDB db) { Assume.assumeTrue(db.getFeatures().isRolloverSupported()); } protected void assumeIsPersistent(final ChronoDB db){ Assume.assumeTrue(db.getFeatures().isPersistent()); } protected void assumeIncrementalBackupIsSupported(final ChronoDB db){ Assume.assumeTrue(db.getFeatures().isIncrementalBackupSupported()); } /** * Asserts that the set of keys (given by the initial varargs arguments) is equal to the result of the query (last * vararg argument). * * <p> * Example: * * <pre> * // assert that the default keyspace consists of the Set {a, b} * assertKeysEqual("a", "b", db.tx().find().inDefaultKeyspace()); * </pre> * * @param objects * The varargs objects. The last argument is the query, all elements before are the expected result keys. */ @SuppressWarnings("unchecked") public static void assertKeysEqual(final Object... objects) { List<Object> list = Lists.newArrayList(objects); Object last = list.get(list.size() - 1); Set<String> keySet = null; if (last instanceof Set) { keySet = ((Set<QualifiedKey>) last).stream().map(QualifiedKey::getKey).collect(Collectors.toSet()); } else if (last instanceof FinalizableQueryBuilder) { keySet = ((FinalizableQueryBuilder) last).getKeysAsSet().stream().map(QualifiedKey::getKey) .collect(Collectors.toSet()); } else { fail("Last element of 'assertKeysEqual' varargs must either be a FinalizableQueryBuilder or a Set<QualifiedKey>!"); } Set<String> keys = list.subList(0, list.size() - 1).stream().map(k -> (String) k).collect(Collectors.toSet()); assertEquals(keys, keySet); } }
6,253
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
InstantiateChronosWith.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/base/InstantiateChronosWith.java
package org.chronos.chronodb.test.base; 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.METHOD) @Retention(RetentionPolicy.RUNTIME) @Repeatable(InstantiateChronosWithRepeatable.class) public @interface InstantiateChronosWith { public String property(); public String value(); }
510
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
InstantiateChronosWithRepeatable.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/base/InstantiateChronosWithRepeatable.java
package org.chronos.chronodb.test.base; 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 @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface InstantiateChronosWithRepeatable { public InstantiateChronosWith[] value(); }
418
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
BranchMetadata.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/BranchMetadata.java
package org.chronos.chronodb.internal.impl; import static com.google.common.base.Preconditions.*; import java.io.Serializable; import org.chronos.chronodb.api.ChronoDBConstants; /** * This class has been superseded by {@link BranchMetadata2} and exists for backwards-compatibility reasons (i.e. there are kryo-instances of this class out there). * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ @Deprecated public class BranchMetadata implements Serializable, IBranchMetadata { // ===================================================================================================================== // STATIC FACTORY METHODS // ===================================================================================================================== public static BranchMetadata createMasterBranchMetadata() { return new BranchMetadata(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, null, 0L); } // ===================================================================================================================== // FIELDS // ===================================================================================================================== private String name; private String parentName; private long branchingTimestamp; // ===================================================================================================================== // CONSTRUCTORS // ===================================================================================================================== protected BranchMetadata() { // default constructor for serialization } public BranchMetadata(final String name, final String parentName, final long branchingTimestamp) { checkNotNull(name, "Precondition violation - argument 'name' must not be NULL!"); // parent name may be null if we have the master branch at hand if (ChronoDBConstants.MASTER_BRANCH_IDENTIFIER.equals(name) == false) { checkNotNull(parentName, "Precondition violation - argument 'parentName' must not be NULL!"); } checkArgument(branchingTimestamp >= 0, "Precondition violation - argument 'branchingTimestamp' must not be negative!"); this.name = name; this.parentName = parentName; this.branchingTimestamp = branchingTimestamp; } // ===================================================================================================================== // PUBLIC API // ===================================================================================================================== @Override public String getName() { return this.name; } @Override public String getParentName() { return this.parentName; } @Override public long getBranchingTimestamp() { return this.branchingTimestamp; } @Override public String getDirectoryName() { // this is a fallback; the ChronoDB-Migrations will replace this class with another one on startup that // fulfills this property. return null; } // ===================================================================================================================== // HASH CODE & EQUALS // ===================================================================================================================== @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (this.branchingTimestamp ^ this.branchingTimestamp >>> 32); result = prime * result + (this.name == null ? 0 : this.name.hashCode()); result = prime * result + (this.parentName == null ? 0 : this.parentName.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; } BranchMetadata other = (BranchMetadata) obj; if (this.branchingTimestamp != other.branchingTimestamp) { return false; } if (this.name == null) { if (other.name != null) { return false; } } else if (!this.name.equals(other.name)) { return false; } if (this.parentName == null) { if (other.parentName != null) { return false; } } else if (!this.parentName.equals(other.parentName)) { return false; } return true; } }
4,247
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
IBranchMetadata.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/IBranchMetadata.java
package org.chronos.chronodb.internal.impl; import static com.google.common.base.Preconditions.*; import org.chronos.chronodb.api.ChronoDBConstants; /** * A common interface for branch metadata objects. * * <p> * Instances of this class should always be treated as immutable value objects. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API */ public interface IBranchMetadata { /** * Creates the {@linkplain IBranchMetadata branch metadata} object for the {@linkplain ChronoDBConstants#MASTER_BRANCH_IDENTIFIER master} branch. * * @return The branch metadata object for the master branch. Never <code>null</code>. */ public static IBranchMetadata createMasterBranchMetadata() { return BranchMetadata2.createMasterBranchMetadata(); } /** * Creates a new {@link IBranchMetadata} object. * * @param name * The name of the branch. Must not be <code>null</code>. * @param parentName * The name of the parent branch. Must not be <code>null</code>, except if the <code>name</code> parameter is {@link ChronoDBConstants#MASTER_BRANCH_IDENTIFIER master}. * @param branchingTimestamp * The branching timestamp. Must not be negative. * @param directoryName * The name of the directory where the branch is stored. May be <code>null</code> if the current Chronos backend does not support/use directory names for branches. * @return The branch metadata object. Never <code>null</code>. */ public static IBranchMetadata create(final String name, final String parentName, final long branchingTimestamp, final String directoryName) { checkNotNull(name, "Precondition violation - argument 'name' must not be NULL!"); // parent name may be null if we have the master branch at hand if (ChronoDBConstants.MASTER_BRANCH_IDENTIFIER.equals(name) == false) { checkNotNull(parentName, "Precondition violation - argument 'parentName' must not be NULL!"); } checkArgument(branchingTimestamp >= 0, "Precondition violation - argument 'branchingTimestamp' must not be negative!"); return new BranchMetadata2(name, parentName, branchingTimestamp, directoryName); } /** * Returns the name of the branch. * * @return The branch name. Never <code>null</code>. */ public String getName(); /** * Returns the name of the parent branch. * * @return The parent branch name. May be <code>null</code> if the current branch is the {@link ChronoDBConstants#MASTER_BRANCH_IDENTIFIER master} branch. */ public String getParentName(); /** * Returns the branching timestamp, i.e. the point in time when this branch was branched away from the parent. * * @return The branching timestamp. Will always be greater than or equal to zero. */ public long getBranchingTimestamp(); /** * Returns the name of the OS directory where this branch is stored. * * <p> * This property may not be available on all backends. Backends that do not support this property should return <code>null</code>. * * @return The name of the directory where the branch data is located. May be <code>null</code> if unsupported. * * @since 0.6.0 */ public String getDirectoryName(); }
3,196
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
DefaultTransactionConfiguration.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/DefaultTransactionConfiguration.java
package org.chronos.chronodb.internal.impl; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.DuplicateVersionEliminationMode; import org.chronos.chronodb.api.conflict.ConflictResolutionStrategy; import org.chronos.chronodb.internal.api.MutableTransactionConfiguration; import org.chronos.chronodb.internal.api.TransactionConfigurationInternal; import java.util.function.Consumer; import static com.google.common.base.Preconditions.*; public class DefaultTransactionConfiguration implements MutableTransactionConfiguration { private Long timestamp; private String branch; private boolean threadSafe; private ConflictResolutionStrategy conflictResolutionStrategy; private DuplicateVersionEliminationMode duplicateVersionEliminationMode; private boolean readOnly; private boolean allowedDuringDateback; private boolean frozen; public DefaultTransactionConfiguration() { this.branch = ChronoDBConstants.MASTER_BRANCH_IDENTIFIER; this.threadSafe = false; this.conflictResolutionStrategy = ConflictResolutionStrategy.DO_NOT_MERGE; this.duplicateVersionEliminationMode = DuplicateVersionEliminationMode.ON_COMMIT; this.readOnly = false; this.allowedDuringDateback = false; this.frozen = false; } public DefaultTransactionConfiguration(TransactionConfigurationInternal other, Consumer<DefaultTransactionConfiguration> modifications) { this.timestamp = other.getTimestamp(); this.branch = other.getBranch(); this.threadSafe = other.isThreadSafe(); this.conflictResolutionStrategy = other.getConflictResolutionStrategy(); this.duplicateVersionEliminationMode = other.getDuplicateVersionEliminationMode(); this.readOnly = other.isReadOnly(); this.allowedDuringDateback = other.isAllowedDuringDateback(); modifications.accept(this); this.freeze(); } @Override public void setBranch(final String branchName) { this.assertNotFrozen(); checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!"); this.branch = branchName; } @Override public String getBranch() { return this.branch; } @Override public void setTimestamp(final long timestamp) { this.assertNotFrozen(); checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); this.timestamp = timestamp; } @Override public Long getTimestamp() { return this.timestamp; } @Override public void setTimestampToNow() { this.assertNotFrozen(); this.timestamp = null; } @Override public boolean isThreadSafe() { return this.threadSafe; } @Override public void setThreadSafe(final boolean threadSafe) { this.assertNotFrozen(); this.threadSafe = threadSafe; } @Override public ConflictResolutionStrategy getConflictResolutionStrategy() { return this.conflictResolutionStrategy; } @Override public void setConflictResolutionStrategy(final ConflictResolutionStrategy strategy) { this.assertNotFrozen(); checkNotNull(strategy, "Precondition violation - argument 'strategy' must not be NULL!"); this.conflictResolutionStrategy = strategy; } @Override public DuplicateVersionEliminationMode getDuplicateVersionEliminationMode() { return this.duplicateVersionEliminationMode; } @Override public void setDuplicateVersionEliminationMode(final DuplicateVersionEliminationMode mode) { this.assertNotFrozen(); checkNotNull(mode, "Precondition violation - argument 'mode' must not be NULL!"); this.duplicateVersionEliminationMode = mode; } @Override public boolean isReadOnly() { return this.readOnly; } @Override public void setReadOnly(final boolean readOnly) { this.assertNotFrozen(); this.readOnly = readOnly; } @Override public boolean isAllowedDuringDateback() { return this.allowedDuringDateback; } @Override public void setAllowedDuringDateback(final boolean allowedDuringDateback) { this.assertNotFrozen(); this.allowedDuringDateback = allowedDuringDateback; } @Override public void freeze() { this.frozen = true; } // ===================================================================================================================== // INTERNAL HELPER METHODS // ===================================================================================================================== private void assertNotFrozen() { if (this.frozen) { throw new IllegalStateException("Cannot modify Transaction Coniguration - it has already been frozen!"); } } }
4,950
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
BranchHeadStatisticsImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/BranchHeadStatisticsImpl.java
package org.chronos.chronodb.internal.impl; import org.chronos.chronodb.api.BranchHeadStatistics; import static com.google.common.base.Preconditions.*; public class BranchHeadStatisticsImpl implements BranchHeadStatistics { // ================================================================================================================= // FIELDS // ================================================================================================================= private long entriesInHead; private long totalEntries; // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= public BranchHeadStatisticsImpl(long entriesInHead, long totalEntries) { checkArgument(entriesInHead >= 0, "Precondition violation, argument 'entriesInHead' must not be negative!"); checkArgument(totalEntries >= 0, "Precondition violation, argument 'totalEntries' must not be negative!"); this.entriesInHead = entriesInHead; this.totalEntries = totalEntries; } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public long getTotalNumberOfEntries() { return this.totalEntries; } @Override public long getNumberOfEntriesInHead() { return this.entriesInHead; } @Override public long getNumberOfEntriesInHistory() { return this.totalEntries - this.entriesInHead; } @Override public double getHeadHistoryRatio() { if (this.totalEntries <= 0) { if(this.entriesInHead > 0){ return this.entriesInHead; }else{ return 1; } } return (double) this.entriesInHead / this.totalEntries; } }
2,116
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChangeSetEntryImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/ChangeSetEntryImpl.java
package org.chronos.chronodb.internal.impl; import static com.google.common.base.Preconditions.*; import java.util.Set; import org.chronos.chronodb.api.ChangeSetEntry; import org.chronos.chronodb.api.PutOption; import org.chronos.chronodb.api.key.QualifiedKey; import com.google.common.collect.ImmutableSet; public class ChangeSetEntryImpl implements ChangeSetEntry { // ================================================================================================================= // STATIC FACTORY METHODS // ================================================================================================================= public static ChangeSetEntry createChange(final QualifiedKey key, final Object newValue, final PutOption... options) { checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); checkNotNull(newValue, "Precondition violation - argument 'newValue' must not be NULL!"); checkNotNull(options, "Precondition violation - argument 'options' must not be NULL!"); return new ChangeSetEntryImpl(key, newValue, options); } public static ChangeSetEntry createDeletion(final QualifiedKey key) { checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); return new ChangeSetEntryImpl(key, null); } // ================================================================================================================= // FIELDS // ================================================================================================================= private final QualifiedKey key; private final Object value; private final Set<PutOption> options; // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= protected ChangeSetEntryImpl(final QualifiedKey key, final Object value, final PutOption... options) { this.key = key; this.value = value; this.options = ImmutableSet.<PutOption> builder().add(options).build(); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public String getKey() { return this.key.getKey(); } @Override public String getKeyspace() { return this.key.getKeyspace(); } @Override public Object getValue() { return this.value; } public Set<PutOption> getOptions() { return this.options; } @Override public boolean isSet() { return this.value != null; } @Override public boolean isRemove() { return this.value == null; } // ================================================================================================================= // HASH CODE & EQUALS // ================================================================================================================= @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.key == null ? 0 : this.key.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; } ChangeSetEntryImpl other = (ChangeSetEntryImpl) obj; if (this.key == null) { if (other.key != null) { return false; } } else if (!this.key.equals(other.key)) { return false; } return true; } }
3,633
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
BranchImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/BranchImpl.java
package org.chronos.chronodb.internal.impl; import static com.google.common.base.Preconditions.*; import java.util.List; import org.chronos.chronodb.api.Branch; import org.chronos.chronodb.internal.api.BranchInternal; import org.chronos.chronodb.internal.api.TemporalKeyValueStore; import com.google.common.collect.Lists; public class BranchImpl implements BranchInternal { // ===================================================================================================================== // STATIC FACTORY // ===================================================================================================================== public static BranchImpl createMasterBranch() { IBranchMetadata masterBranchMetadata = IBranchMetadata.createMasterBranchMetadata(); return new BranchImpl(masterBranchMetadata, null); } public static BranchImpl createBranch(final IBranchMetadata metadata, final Branch parentBranch) { checkNotNull(metadata, "Precondition violation - argument 'metadata' must not be NULL!"); checkNotNull(parentBranch, "Precondition violation - argument 'parentBranch' must not be NULL!"); return new BranchImpl(metadata, parentBranch); } // ===================================================================================================================== // FIELDS // ===================================================================================================================== private final IBranchMetadata metadata; private final Branch origin; private TemporalKeyValueStore tkvs; // ===================================================================================================================== // CONSTRUCTOR // ===================================================================================================================== protected BranchImpl(final IBranchMetadata metadata, final Branch origin) { checkNotNull(metadata, "Precondition violation - argument 'metadata' must not be NULL!"); // if we have an origin, its name must match the one stored in the metadata if (origin != null) { checkArgument(origin.getName().equals(metadata.getParentName()), "Precondition violation - argument 'origin' references a different name " + "than the parent branch name in the branch metadata!"); } this.metadata = metadata; this.origin = origin; } // ===================================================================================================================== // PUBLIC API // ===================================================================================================================== @Override public String getName() { return this.metadata.getName(); } @Override public Branch getOrigin() { return this.origin; } @Override public long getBranchingTimestamp() { return this.metadata.getBranchingTimestamp(); } @Override public List<Branch> getOriginsRecursive() { if (this.origin == null) { // we are the master branch; by definition, we return an empty list (see JavaDoc). return Lists.newArrayList(); } else { // we are not the master branch. Ask the origin to create the list for us List<Branch> origins = this.getOrigin().getOriginsRecursive(); // ... and add our immediate parent to it. origins.add(this.getOrigin()); return origins; } } @Override public long getNow() { if (this.origin != null) { // on a non-master branch, take the maximum of last commit and branching timestamp return Math.max(this.getBranchingTimestamp(), this.tkvs.getNow()); } else { // on the master branch, only the timestamp of the last successful commit decides. return this.tkvs.getNow(); } } @Override public String getDirectoryName() { return this.metadata.getDirectoryName(); } // ===================================================================================================================== // HASH CODE & EQUALS // ===================================================================================================================== @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.metadata == null ? 0 : this.metadata.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; } BranchImpl other = (BranchImpl) obj; if (this.metadata == null) { if (other.metadata != null) { return false; } } else if (!this.metadata.equals(other.metadata)) { return false; } return true; } // ===================================================================================================================== // TO STRING // ===================================================================================================================== @Override public String toString() { String originName = "NULL"; if (this.origin != null) { originName = this.origin.getName(); } return "Branch['" + this.getName() + "' origin='" + originName + "' branchingTimestamp=" + this.getBranchingTimestamp() + "]"; } // ===================================================================================================================== // INTERNAL API // ===================================================================================================================== @Override public IBranchMetadata getMetadata() { return this.metadata; } @Override public TemporalKeyValueStore getTemporalKeyValueStore() { return this.tkvs; } @Override public void setTemporalKeyValueStore(final TemporalKeyValueStore tkvs) { checkNotNull(tkvs, "Precondition violation - argument 'tkvs' must not be NULL!"); this.tkvs = tkvs; } }
5,807
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
MatrixUtils.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/MatrixUtils.java
package org.chronos.chronodb.internal.impl; import com.google.common.collect.Iterators; import com.google.common.collect.PeekingIterator; import org.chronos.chronodb.api.BranchHeadStatistics; import org.chronos.chronodb.internal.impl.temporal.UnqualifiedTemporalKey; import java.util.Iterator; import java.util.Objects; import java.util.UUID; import java.util.function.Function; import static com.google.common.base.Preconditions.*; public class MatrixUtils { // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= protected MatrixUtils() { throw new IllegalStateException("MatrixMap must not be instantiated!"); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= /** * Generates and returns a random name for a matrix map. * * @return A random matrix map name. Never <code>null</code>. */ public static String generateRandomName() { return "MATRIX_" + UUID.randomUUID().toString().replace("-", "_"); } /** * Checks if the given string is a valid matrix map name. * * @param mapName The map name to check. May be <code>null</code>. * @return <code>true</code> if the given map name is a valid matrix map name, or <code>false</code> if it is syntactically invalid or <code>null</code>. */ public static boolean isValidMatrixTableName(final String mapName) { if (mapName == null) { return false; } String tablenNameRegex = "MATRIX_[a-zA-Z0-9_]+"; return mapName.matches(tablenNameRegex); } /** * Asserts that the given map name is a valid matrix map name. * * <p> * If the map name matches the syntax, this method does nothing. Otherwise, an exception is thrown. * * @param mapName The map name to verify. * @throws NullPointerException Thrown if the map name is <code>null</code>. * @throws IllegalArgumentException Thrown if the map name is no syntactically valid matrix table name. * @see #isValidMatrixTableName(String) */ public static void assertIsValidMatrixTableName(final String mapName) { if (mapName == null) { throw new IllegalArgumentException("NULL is no valid Matrix Map name!"); } if (isValidMatrixTableName(mapName) == false) { throw new IllegalArgumentException("The map name '" + mapName + "' is no valid Matrix Map name!"); } } /** * Calculates the head statistics given an iterator over the keys (in ascending order) and a function to check if an entry is a deletion. * * @param ascendingKeyIterator The iterator to use. Must return keys in ascending order. Must not be <code>null</code>. * @param isDeletionCheck A function to check if the entry for a given temporal key represents a deletion. Must not be <code>null</code>. Must return <code>true</code> if the entry for a given temporal key represents a deletion, or <code>false</code> if the entry represents an insert or an update. * @return The head statistics. Never <code>null</code>. */ public static BranchHeadStatistics calculateBranchHeadStatistics(Iterator<UnqualifiedTemporalKey> ascendingKeyIterator, Function<UnqualifiedTemporalKey, Boolean> isDeletionCheck) { checkNotNull(ascendingKeyIterator, "Precondition violation - argument 'ascendingKeyIterator' must not be NULL!"); checkNotNull(isDeletionCheck, "Precondition violation - argument 'isDeletionCheck' must not be NULL!"); long totalEntries = 0; long entriesInHead = 0; PeekingIterator<UnqualifiedTemporalKey> iterator = Iterators.peekingIterator(ascendingKeyIterator); while (iterator.hasNext()) { UnqualifiedTemporalKey entryKey = iterator.next(); UnqualifiedTemporalKey nextEntry = iterator.hasNext() ? iterator.peek() : null; if (isLatestEntryForKey(entryKey, nextEntry)) { // this is the latest entry in the history of this user key. if (isDeletionCheck.apply(entryKey)) { // the last entry is a deletion, it does not contribute to the // head revision (only to the history) totalEntries++; } else { // the last entry is a valid key-value pair in the head revision. entriesInHead++; totalEntries++; } } else { // the next entry in the matrix also references the same user key, // so this entry is part of the history and does not contribute to // the head version. totalEntries++; } } return new BranchHeadStatisticsImpl(entriesInHead, totalEntries); } private static boolean isLatestEntryForKey(final UnqualifiedTemporalKey entryKey, final UnqualifiedTemporalKey nextKey) { if (nextKey == null) { // the matrix has no next entry, therefore the current entry is the // last in the history of this key return true; } if (!Objects.equals(entryKey.getKey(), nextKey.getKey())) { // the next entry in the matrix is about a different user key, therefore // the current entry is the last in the history of our user key. return true; } return false; } }
5,819
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ConflictResolutionStrategyLoader.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/ConflictResolutionStrategyLoader.java
package org.chronos.chronodb.internal.impl; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import org.chronos.chronodb.api.conflict.ConflictResolutionStrategy; import org.chronos.chronodb.internal.api.ChronoDBConfiguration; public class ConflictResolutionStrategyLoader { /** * Loads a {@link ConflictResolutionStrategy} instance with the given name. * * <p> * This is a direct implementation of the semantics specified in * {@link ChronoDBConfiguration#COMMIT_CONFLICT_RESOLUTION_STRATEGY}. Please refer to its JavaDocs for details. * * @param name * The name of the strategy to load. If <code>null</code> or whitespace-only string is passed, * {@link ConflictResolutionStrategy#DO_NOT_MERGE} will be returned as a default. Can be the name of a * standard strategy, or the fully qualified name of a custom class that implements the * {@link ConflictResolutionStrategy} interface and has a default constructor. * * @return The loaded conflict resolution strategy. Never <code>null</code>. */ public static ConflictResolutionStrategy load(final String name) { if (name == null || name.trim().isEmpty()) { // use the default return ConflictResolutionStrategy.DO_NOT_MERGE; } String className = name.trim(); // check the predefined strategies if (className.equals("DO_NOT_MERGE")) { return ConflictResolutionStrategy.DO_NOT_MERGE; } else if (className.equals("OVERWRITE_WITH_SOURCE")) { return ConflictResolutionStrategy.OVERWRITE_WITH_SOURCE; } else if (className.equals("OVERWRITE_WITH_TARGET")) { return ConflictResolutionStrategy.OVERWRITE_WITH_TARGET; } // no predefined strategy matched. Try to find the custom class Class<?> strategyClass = null; try { strategyClass = Class.forName(className); } catch (Exception e) { throw new IllegalArgumentException( "The parameter " + ChronoDBConfiguration.COMMIT_CONFLICT_RESOLUTION_STRATEGY + " was set to '" + className + "' which is neither a predefined strategy nor the qualified name of a class!", e); } if (ConflictResolutionStrategy.class.isAssignableFrom(strategyClass) == false) { throw new IllegalArgumentException("The parameter " + ChronoDBConfiguration.COMMIT_CONFLICT_RESOLUTION_STRATEGY + " was set to '" + className + "' which refers to a fully qualified class name, but that class does not implement the required interface '" + ConflictResolutionStrategy.class.getName() + "'!"); } if (strategyClass.isInterface() || Modifier.isAbstract(strategyClass.getModifiers())) { throw new IllegalArgumentException("The parameter " + ChronoDBConfiguration.COMMIT_CONFLICT_RESOLUTION_STRATEGY + " was set to '" + className + "' which refers to a fully qualified class name, but that class is either abstract or an interface!"); } try { Constructor<?> constructor = strategyClass.getConstructor(); ConflictResolutionStrategy strategy = (ConflictResolutionStrategy) constructor.newInstance(); return strategy; } catch (Exception e) { throw new IllegalArgumentException("The parameter " + ChronoDBConfiguration.COMMIT_CONFLICT_RESOLUTION_STRATEGY + " was set to '" + className + "' which refers to a fully qualified class name, but that class could not be instantiated. Does it have a default (no-argument) contructor?", e); } } }
3,422
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
BranchMetadata2.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/BranchMetadata2.java
package org.chronos.chronodb.internal.impl; import static com.google.common.base.Preconditions.*; import java.io.Serializable; import org.chronos.chronodb.api.ChronoDBConstants; /** * An enhanced version of {@link BranchMetadata} that additionally includes the {@link IBranchMetadata#getDirectoryName() directory name} property. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * * @since 0.6.0 */ public class BranchMetadata2 implements Serializable, IBranchMetadata { // ===================================================================================================================== // STATIC FACTORY METHODS // ===================================================================================================================== public static BranchMetadata2 createMasterBranchMetadata() { return new BranchMetadata2(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, null, 0L, ChronoDBConstants.MASTER_BRANCH_IDENTIFIER); } // ===================================================================================================================== // FIELDS // ===================================================================================================================== private String name; private String parentName; private String directoryName; private long branchingTimestamp; // ===================================================================================================================== // CONSTRUCTORS // ===================================================================================================================== protected BranchMetadata2() { // default constructor for serialization } public BranchMetadata2(final String name, final String parentName, final long branchingTimestamp, final String directoryName) { checkNotNull(name, "Precondition violation - argument 'name' must not be NULL!"); // parent name may be null if we have the master branch at hand if (ChronoDBConstants.MASTER_BRANCH_IDENTIFIER.equals(name) == false) { checkNotNull(parentName, "Precondition violation - argument 'parentName' must not be NULL!"); } checkArgument(branchingTimestamp >= 0, "Precondition violation - argument 'branchingTimestamp' must not be negative!"); this.name = name; this.parentName = parentName; this.branchingTimestamp = branchingTimestamp; this.directoryName = directoryName; } // ===================================================================================================================== // PUBLIC API // ===================================================================================================================== @Override public String getName() { return this.name; } @Override public String getParentName() { return this.parentName; } @Override public long getBranchingTimestamp() { return this.branchingTimestamp; } @Override public String getDirectoryName() { return this.directoryName; } // ===================================================================================================================== // HASH CODE & EQUALS // ===================================================================================================================== @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (this.branchingTimestamp ^ this.branchingTimestamp >>> 32); result = prime * result + (this.directoryName == null ? 0 : this.directoryName.hashCode()); result = prime * result + (this.name == null ? 0 : this.name.hashCode()); result = prime * result + (this.parentName == null ? 0 : this.parentName.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; } BranchMetadata2 other = (BranchMetadata2) obj; if (this.branchingTimestamp != other.branchingTimestamp) { return false; } if (this.directoryName == null) { if (other.directoryName != null) { return false; } } else if (!this.directoryName.equals(other.directoryName)) { return false; } if (this.name == null) { if (other.name != null) { return false; } } else if (!this.name.equals(other.name)) { return false; } if (this.parentName == null) { if (other.parentName != null) { return false; } } else if (!this.parentName.equals(other.parentName)) { return false; } return true; } }
4,537
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoDBBaseConfiguration.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/ChronoDBBaseConfiguration.java
package org.chronos.chronodb.internal.impl; import org.chronos.chronodb.api.CommitMetadataFilter; import org.chronos.chronodb.api.DuplicateVersionEliminationMode; import org.chronos.chronodb.api.conflict.ConflictResolutionStrategy; import org.chronos.chronodb.internal.api.CacheType; import org.chronos.chronodb.internal.api.ChronoDBConfiguration; import org.chronos.common.configuration.AbstractConfiguration; import org.chronos.common.configuration.Comparison; import org.chronos.common.configuration.annotation.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Namespace(ChronoDBConfiguration.NAMESPACE) public abstract class ChronoDBBaseConfiguration extends AbstractConfiguration implements ChronoDBConfiguration { private static final Logger log = LoggerFactory.getLogger(ChronoDBBaseConfiguration.class); // ===================================================================================================================== // DEFAULT SETTINGS // ===================================================================================================================== private static final long DEFAULT__STORAGE_BACKEND_CACHE = 1024L * 1024L * 200L; // 200 MB (in bytes) // ===================================================================================================================== // FIELDS // ===================================================================================================================== // general settings @Parameter(key = DEBUG) private boolean debugModeEnabled = false; @Parameter(key = MBEANS_ENABLED) private boolean mbeansEnabled = true; @EnumFactoryMethod("fromString") @Parameter(key = STORAGE_BACKEND) private String backendType; @Parameter(key = STORAGE_BACKEND_CACHE) @IgnoredIf(field = "backendType", comparison = Comparison.IS_SET_TO, compareValue = "JDBC") @IgnoredIf(field = "backendType", comparison = Comparison.IS_SET_TO, compareValue = "FILE") @IgnoredIf(field = "backendType", comparison = Comparison.IS_SET_TO, compareValue = "INMEMORY") private long storageBackendCacheMaxSize = DEFAULT__STORAGE_BACKEND_CACHE; @Parameter(key = CACHING_ENABLED) private boolean cachingEnabled = false; @Parameter(key = CACHE_MAX_SIZE) @RequiredIf(field = "cachingEnabled", comparison = Comparison.IS_SET_TO, compareValue = "true") private Integer cacheMaxSize; @EnumFactoryMethod("fromString") @IgnoredIf(field = "cachingEnabled", comparison = Comparison.IS_SET_TO, compareValue = "false") @Parameter(key = CACHE_TYPE, optional = true) private CacheType cacheType = CacheType.MOSAIC; @IgnoredIf(field = "cacheType", comparison = Comparison.IS_NOT_SET_TO, compareValue = "HEAD_FIRST") @Parameter(key = CACHE_HEADFIRST_PREFERRED_BRANCH, optional = true) private String cacheHeadFirstPreferredBranch = null; @IgnoredIf(field = "cacheType", comparison = Comparison.IS_NOT_SET_TO, compareValue = "HEAD_FIRST") @Parameter(key = CACHE_HEADFIRST_PREFERRED_KEYSPACE, optional = true) private String cacheHeadFirstPreferredKeyspace = null; @Parameter(key = QUERY_CACHE_ENABLED) private boolean indexQueryCachingEnabled = false; @Parameter(key = QUERY_CACHE_MAX_SIZE) @RequiredIf(field = "indexQueryCachingEnabled", comparison = Comparison.IS_SET_TO, compareValue = "true") private Integer indexQueryCacheMaxSize; @Parameter(key = ASSUME_CACHE_VALUES_ARE_IMMUTABLE) @RequiredIf(field = "cachingEnabled", comparison = Comparison.IS_SET_TO, compareValue = "true") private boolean assumeCachedValuesAreImmutable = false; @Parameter(key = COMMIT_CONFLICT_RESOLUTION_STRATEGY, optional = true) private String conflictResolutionStrategyName; @EnumFactoryMethod("fromString") @Parameter(key = DUPLICATE_VERSION_ELIMINATION_MODE, optional = true) private DuplicateVersionEliminationMode duplicateVersionEliminationMode = DuplicateVersionEliminationMode.ON_COMMIT; @Parameter(key = COMMIT_METADATA_FILTER_CLASS, optional = true) private String commitMetadataFilterClassName = null; @Parameter(key = PERFORMANCE_LOGGING_FOR_COMMITS, optional = true) private boolean isCommitPerformanceLoggingActive = false; @Parameter(key = READONLY, optional = true) @IgnoredIf(field = "backendType", comparison = Comparison.IS_SET_TO, compareValue = "inmemory") private boolean readOnly = false; // ================================================================================================================= // CACHES // ================================================================================================================= private transient ConflictResolutionStrategy conflictResolutionStrategy; // ================================================================================================================= // GENERAL SETTINGS // ================================================================================================================= @Override public boolean isDebugModeEnabled() { return this.debugModeEnabled; } @Override public boolean isMBeanIntegrationEnabled() { return this.mbeansEnabled; } @Override public String getBackendType() { return this.backendType; } @Override public long getStorageBackendCacheMaxSize() { return this.storageBackendCacheMaxSize; } @Override public boolean isCachingEnabled() { return this.cachingEnabled; } @Override public Integer getCacheMaxSize() { return this.cacheMaxSize; } @Override public CacheType getCacheType() { return this.cacheType; } @Override public String getCacheHeadFirstPreferredBranch() { return this.cacheHeadFirstPreferredBranch; } @Override public String getCacheHeadFirstPreferredKeyspace() { return this.cacheHeadFirstPreferredKeyspace; } @Override public boolean isIndexQueryCachingEnabled() { return this.indexQueryCachingEnabled; } @Override public Integer getIndexQueryCacheMaxSize() { return this.indexQueryCacheMaxSize; } @Override public boolean isAssumeCachedValuesAreImmutable() { return this.assumeCachedValuesAreImmutable; } @Override public ConflictResolutionStrategy getConflictResolutionStrategy() { if (this.conflictResolutionStrategy == null) { // setting was not yet resolved, do it now this.conflictResolutionStrategy = ConflictResolutionStrategyLoader .load(this.conflictResolutionStrategyName); // we already resolved this setting, use the cached instance } return this.conflictResolutionStrategy; } @Override public DuplicateVersionEliminationMode getDuplicateVersionEliminationMode() { return this.duplicateVersionEliminationMode; } @Override public Class<? extends CommitMetadataFilter> getCommitMetadataFilterClass() { if (this.commitMetadataFilterClassName == null || this.commitMetadataFilterClassName.trim().isEmpty()) { return null; } try { return (Class<? extends CommitMetadataFilter>) Class.forName(this.commitMetadataFilterClassName.trim()); } catch (ClassNotFoundException | NoClassDefFoundError e) { log.warn("Configuration warning: could not find Commit Metadata Filter class: '" + this.commitMetadataFilterClassName.trim() + "' (" + e.getClass().getSimpleName() + ")! No filter will be instantiated."); return null; } } @Override public boolean isCommitPerformanceLoggingActive() { return isCommitPerformanceLoggingActive; } @Override public boolean isReadOnly() { return this.readOnly; } }
7,928
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ConverterRegistry.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dump/ConverterRegistry.java
package org.chronos.chronodb.internal.impl.dump; import static com.google.common.base.Preconditions.*; import java.util.Map; import org.chronos.chronodb.api.DumpOption.DefaultConverterOption; import org.chronos.chronodb.api.dump.ChronoConverter; import org.chronos.chronodb.api.dump.annotations.ChronosExternalizable; import org.chronos.common.util.ReflectionUtils; import com.google.common.collect.Maps; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ConverterRegistry { private static final Logger log = LoggerFactory.getLogger(ConverterRegistry.class); private final Map<Class<?>, ChronoConverter<?, ?>> defaultConverters = Maps.newHashMap(); private final Map<Class<? extends ChronoConverter<?, ?>>, ChronoConverter<?, ?>> converterCache = Maps.newHashMap(); // ===================================================================================================================== // CONSTRUCTOR // ===================================================================================================================== public ConverterRegistry(final DumpOptions options) { checkNotNull(options, "Precondition violation - argument 'options' must not be NULL!"); this.loadDefaultConverters(options); } public ChronoConverter<?, ?> getConverterForObject(final Object object) { if (object == null) { return null; } Class<?> converterClass = this.getAnnotatedConverterClass(object); if (converterClass != null) { // found a converter annotation, get the matching instance return this.getOrCreateConverterWithClass(converterClass); } if (converterClass == null) { // the object itself has no converter, check the default converters ChronoConverter<?, ?> converter = this.defaultConverters.get(object.getClass()); if (converter != null) { // found a default converter return converter; } } // neither an annotation was present nor a default converter... return null; } public boolean isDefaultConverter(final ChronoConverter<?, ?> converter) { if (converter == null) { return false; } return this.defaultConverters.values().contains(converter); } public ChronoConverter<?, ?> getConverterByClassName(final String converterClassName) { try { Class<?> converterClass = Class.forName(converterClassName); return this.getOrCreateConverterWithClass(converterClass); } catch (ClassNotFoundException e) { log.error("Could not find ChronoConverter with class '" + converterClassName + "'!", e); return null; } } // ===================================================================================================================== // INTERNAL HELPER METHODS // ===================================================================================================================== private void loadDefaultConverters(final DumpOptions options) { checkNotNull(options, "Precondition violation - argument 'options' must not be NULL!"); for (DefaultConverterOption option : options.getDefaultConverterOptions()) { Class<?> modelClass = option.getType(); ChronoConverter<?, ?> converter = option.getConverter(); this.defaultConverters.put(modelClass, converter); this.registerConverterInCache(converter); } } @SuppressWarnings("unchecked") private void registerConverterInCache(final ChronoConverter<?, ?> converter) { this.converterCache.put((Class<? extends ChronoConverter<?, ?>>) converter.getClass(), converter); } private ChronoConverter<?, ?> getOrCreateConverterWithClass(final Class<?> converterClass) { checkNotNull(converterClass, "Precondition violation - argument 'converterClass' must not be NULL!"); // first, check if it's in the cache ChronoConverter<?, ?> cachedConverter = this.converterCache.get(converterClass); if (cachedConverter != null) { return cachedConverter; } // we didn't find it in the cache, instantiate it, cache it and return it try { ChronoConverter<?, ?> converter = (ChronoConverter<?, ?>) ReflectionUtils.instantiate(converterClass); this.registerConverterInCache(converter); return converter; } catch (Exception e) { log.warn("Could not instantiate Plain-Text-Converter class '" + converterClass.getName() + "'."); return null; } } private Class<?> getAnnotatedConverterClass(final Object value) { ChronosExternalizable annotation = value.getClass().getAnnotation(ChronosExternalizable.class); if (annotation == null) { return null; } Class<? extends ChronoConverter<?, ?>> converterClass = annotation.converterClass(); return converterClass; } }
4,582
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoDBDumpUtil.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dump/ChronoDBDumpUtil.java
package org.chronos.chronodb.internal.impl.dump; import com.google.common.collect.HashMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.SetMultimap; import org.chronos.chronodb.api.*; import org.chronos.chronodb.api.dump.ChronoConverter; import org.chronos.chronodb.api.dump.annotations.ChronosExternalizable; import org.chronos.chronodb.api.exceptions.ChronoDBException; import org.chronos.chronodb.api.exceptions.ChronoDBSerializationException; import org.chronos.chronodb.api.exceptions.ChronoDBStorageBackendException; import org.chronos.chronodb.api.indexing.Indexer; import org.chronos.chronodb.api.key.ChronoIdentifier; import org.chronos.chronodb.internal.api.*; import org.chronos.chronodb.internal.api.dateback.log.DatebackOperation; import org.chronos.chronodb.internal.api.index.IndexManagerInternal; import org.chronos.chronodb.internal.api.stream.ChronoDBEntry; import org.chronos.chronodb.internal.api.stream.CloseableIterator; import org.chronos.chronodb.internal.api.stream.ObjectInput; import org.chronos.chronodb.internal.api.stream.ObjectOutput; import org.chronos.chronodb.internal.impl.IBranchMetadata; import org.chronos.chronodb.internal.impl.dateback.log.*; import org.chronos.chronodb.internal.impl.dateback.log.v2.TransformCommitOperation2; import org.chronos.chronodb.internal.impl.dump.base.ChronoDBDumpElement; import org.chronos.chronodb.internal.impl.dump.entry.ChronoDBDumpBinaryEntry; import org.chronos.chronodb.internal.impl.dump.entry.ChronoDBDumpEntry; import org.chronos.chronodb.internal.impl.dump.entry.ChronoDBDumpPlainEntry; import org.chronos.chronodb.internal.impl.dump.meta.*; import org.chronos.chronodb.internal.impl.dump.meta.dateback.*; import org.chronos.chronodb.internal.impl.index.SecondaryIndexImpl; import org.chronos.common.util.ReflectionUtils; import org.chronos.common.version.ChronosVersion; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.Map.Entry; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.*; public class ChronoDBDumpUtil { private static final Logger log = LoggerFactory.getLogger(ChronoDBDumpUtil.class); // ===================================================================================================================== // PUBLIC API // ===================================================================================================================== public static void dumpDBContentsToOutput(final ChronoDBInternal db, final ObjectOutput output, final DumpOptions options) { checkNotNull(db, "Precondition violation - argument 'db' must not be NULL!"); checkNotNull(output, "Precondition violation - argument 'output' must not be NULL!"); checkNotNull(options, "Precondition violation - argument 'options' must not be NULL!"); // stream out data using a sequence writer that fills a root array try { // calculate the metadata we need to write as the first object ChronoDBDumpMetadata dbMetadata = extractMetadata(db, true); // write the DB data into the dump file output.write(dbMetadata); // set up some caches and variables we are going to need later SerializationManager sm = db.getSerializationManager(); boolean forceBinary = options.isForceBinaryEncodingEnabled(); ConverterRegistry converters = new ConverterRegistry(options); // now, stream in the entries from the database try (CloseableIterator<ChronoDBEntry> entryStream = db.entryStream()) { exportEntriesToDumpFormat(output, sm, forceBinary, converters, entryStream); } } catch (Exception e) { throw new ChronoDBStorageBackendException("Failed to write Chronos DB Dump! See root cause for details.", e); } finally { output.close(); } } public static void exportEntriesToDumpFormat(final ObjectOutput output, final SerializationManager sm, final boolean forceBinary, final ConverterRegistry converters, final CloseableIterator<ChronoDBEntry> entryStream) { while (entryStream.hasNext()) { ChronoDBEntry entry = entryStream.next(); // convert the entry to the dump entry, depending on the settings ChronoDBDumpEntry<?> dumpEntry = null; if (forceBinary) { dumpEntry = convertToBinaryEntry(entry); } else { dumpEntry = convertToDumpEntry(entry, sm, converters); } // write our entry into the dump output.write(dumpEntry); } } public static void readDumpContentsFromInput(final ChronoDBInternal db, final ObjectInput input, final DumpOptions options) { checkNotNull(db, "Precondition violation - argument 'db' must not be NULL!"); checkNotNull(input, "Precondition violation - argument 'input' must not be NULL!"); checkNotNull(options, "Precondition violation - argument 'options' must not be NULL!"); try { // create the converter registry based on the options ConverterRegistry converters = new ConverterRegistry(options); // the first element should ALWAYS be the metadata ChronoDBDumpMetadata metadata = readMetadata(input); // with the metadata, we set up the branches createBranches(db, metadata); // load the elements loadEntries(db, input, metadata, converters, options); // load the dateback operations loadDatebackLog(db, metadata); // set up the indexers if (db.requiresAutoReindexAfterDumpRead()) { setupIndexersAndReindex(db, metadata); } else { setupIndexers(db, metadata); } } catch (Exception e) { throw new ChronoDBStorageBackendException("Failed to load DB dump!", e); } } public static ChronoConverter<?, ?> getAnnotatedConverter(final Object value) { ChronosExternalizable annotation = value.getClass().getAnnotation(ChronosExternalizable.class); if (annotation == null) { return null; } Class<? extends ChronoConverter<?, ?>> converterClass = annotation.converterClass(); try { return ReflectionUtils.instantiate(converterClass); } catch (Exception e) { log.warn("Could not instantiate Plain-Text-Converter class '" + converterClass.getName() + "' for annotated class '" + value.getClass().getName() + "'. Falling back to binary."); return null; } } public static boolean isWellKnownObject(final Object object) { if (object == null) { return true; } if (ReflectionUtils.isPrimitiveOrWrapperClass(object.getClass())) { // we support all primitives and their wrapper classes as well-known classes return true; } if (object instanceof String) { // we treat string as well-known class return true; } if (object.getClass().isEnum()) { // we treat enums as well-known elements return true; } if (object instanceof Collection<?>) { Collection<?> collection = (Collection<?>) object; // check if it's a well-known collection class if (isWellKnownCollectionClass(collection.getClass()) == false) { // nope, we don't know this collection class return false; } // make sure that all members are of well-known types for (Object element : collection) { if (isWellKnownObject(element) == false) { // a non-well-known element resides in the collection -> the object as a whole is not well-known return false; } } // we know the collection type, and all elements (recursively) -> the object is well-known return true; } if (object instanceof Map<?, ?>) { Map<?, ?> map = (Map<?, ?>) object; if (isWellKnownMapClass(map.getClass()) == false) { // we don't know this map class return false; } // make sure that all entries are of well-known types for (Entry<?, ?> entry : map.entrySet()) { if (isWellKnownObject(entry.getKey()) == false) { return false; } if (isWellKnownObject(entry.getValue()) == false) { return false; } } // we know the map type, and all elements (recursively) -> the object is well-known return true; } // in any other case, the object is no well-known type return false; } private static boolean isWellKnownCollectionClass(final Class<?> clazz) { if (clazz.equals(HashSet.class)) { return true; } else if (clazz.equals(ArrayList.class)) { return true; } else if (clazz.equals(LinkedList.class)) { return true; } // unknown collection type return false; } private static boolean isWellKnownMapClass(final Class<?> clazz) { if (clazz.equals(HashMap.class)) { return true; } // unknown map type return false; } // ===================================================================================================================== // SERIALIZATION / DUMP WRITE METHODS // ===================================================================================================================== public static ChronoDBDumpMetadata extractMetadata(final ChronoDBInternal db, boolean includeCommitMetadata) { checkNotNull(db, "Precondition violation - argument 'db' must not be NULL!"); ChronoDBDumpMetadata dbDumpMetadata = new ChronoDBDumpMetadata(); dbDumpMetadata.setCreationDate(new Date()); dbDumpMetadata.setChronosVersion(ChronosVersion.getCurrentVersion()); // copy branch metadata BranchManager branchManager = db.getBranchManager(); for (Branch branch : branchManager.getBranches()) { BranchDumpMetadata branchDump = new BranchDumpMetadata(branch); dbDumpMetadata.getBranchDumpMetadata().add(branchDump); } if (includeCommitMetadata) { // copy commit metadata for (Branch branch : branchManager.getBranches()) { String branchName = branch.getName(); CommitMetadataStore commitStore = ((BranchInternal) branch).getTemporalKeyValueStore().getCommitMetadataStore(); List<Entry<Long, Object>> commits = commitStore.getCommitMetadataBefore(System.currentTimeMillis() + 1, Integer.MAX_VALUE, true); for (Entry<Long, Object> commit : commits) { Long timestamp = commit.getKey(); Object metadata = commit.getValue(); CommitDumpMetadata commitDump = new CommitDumpMetadata(branchName, timestamp, metadata); dbDumpMetadata.getCommitDumpMetadata().add(commitDump); } } } // copy indexer metadata IndexManager indexManager = db.getIndexManager(); Set<SecondaryIndex> indices = indexManager.getIndices(); for (SecondaryIndex index : indices) { IndexerDumpMetadataV2 indexDump = new IndexerDumpMetadataV2(index); dbDumpMetadata.getIndexerDumpMetadata().add(indexDump); } // copy dateback metadata DatebackManager datebackManager = db.getDatebackManager(); List<DatebackOperation> datebackOperations = datebackManager.getAllPerformedDatebackOperations(); for (DatebackOperation datebackOperation : datebackOperations) { DatebackLog log = exportDatebackOperation(datebackOperation); dbDumpMetadata.getDatebackLog().add(log); } return dbDumpMetadata; } private static ChronoDBDumpBinaryEntry convertToBinaryEntry(final ChronoDBEntry entry) { return new ChronoDBDumpBinaryEntry(entry.getIdentifier(), entry.getValue()); } @SuppressWarnings({"unchecked", "rawtypes"}) public static ChronoDBDumpEntry<?> convertToDumpEntry(final ChronoDBEntry entry, final SerializationManager serializationManager, final ConverterRegistry converters) { ChronoDBDumpEntry<?> dumpEntry; byte[] serializedValue = entry.getValue(); if (serializedValue == null || serializedValue.length < 1) { // this entry is a deletion and has no value; it makes no difference if we // write it out as a serialized entry or a plain-text entry. dumpEntry = convertToBinaryEntry(entry); } else { // deserialize the value and check if it is plain-text enabled Object deserializedValue = serializationManager.deserialize(serializedValue); ChronoConverter converter = converters.getConverterForObject(deserializedValue); // if we have a plain text converter, use it Object externalRepresentation = null; if (converter != null) { try { externalRepresentation = converter.writeToOutput(deserializedValue); if (externalRepresentation == null) { log.error("Plain text converter '" + converter.getClass() + "' produced NULL! Falling back to binary."); // set the plain text to NULL, in case that it was empty externalRepresentation = null; converter = null; } else { // we successfully converted the entry. We can discard the converter // in the output if we used a default converter. if (converters.isDefaultConverter(converter)) { // it's a default converter, don't include it in the output converter = null; } } } catch (Exception e) { log.error("Chrono converter '" + converter.getClass() + "' produced an error! Falling back to binary. Exception is: " + e.toString()); } } else { // we did not find an explicit converter; maybe it's a well-known object? if (isWellKnownObject(deserializedValue)) { // it's a well-known object, we can use it directly as external representation externalRepresentation = deserializedValue; converter = null; } } // see if the plain text conversion worked if (externalRepresentation != null) { // conversion was okay; use it dumpEntry = new ChronoDBDumpPlainEntry(entry.getIdentifier(), externalRepresentation, converter); } else { // plain text conversion failed, fall back to binary dumpEntry = convertToBinaryEntry(entry); } } return dumpEntry; } private static DatebackLog exportDatebackOperation(final DatebackOperation datebackOperation) { checkNotNull(datebackOperation, "Precondition violation - argument 'datebackOperation' must not be NULL!"); if (datebackOperation instanceof InjectEntriesOperation) { InjectEntriesOperation op = (InjectEntriesOperation) datebackOperation; return new InjectEntriesOperationLog( op.getId(), op.getBranch(), op.getWallClockTime(), op.getOperationTimestamp(), op.getInjectedKeys(), op.isCommitMetadataOverride() ); } else if (datebackOperation instanceof PurgeCommitsOperation) { PurgeCommitsOperation op = (PurgeCommitsOperation) datebackOperation; return new PurgeCommitsOperationLog( op.getId(), op.getBranch(), op.getWallClockTime(), op.getCommitTimestamps() ); } else if (datebackOperation instanceof PurgeEntryOperation) { PurgeEntryOperation op = (PurgeEntryOperation) datebackOperation; return new PurgeEntryOperationLog( op.getId(), op.getBranch(), op.getWallClockTime(), op.getOperationTimestamp(), op.getKeyspace(), op.getKey() ); } else if (datebackOperation instanceof PurgeKeyOperation) { PurgeKeyOperation op = (PurgeKeyOperation) datebackOperation; return new PurgeKeyOperationLog( op.getId(), op.getBranch(), op.getWallClockTime(), op.getKeyspace(), op.getKey(), op.getFromTimestamp(), op.getToTimestamp() ); } else if (datebackOperation instanceof PurgeKeyspaceOperation) { PurgeKeyspaceOperation op = (PurgeKeyspaceOperation) datebackOperation; return new PurgeKeyspaceOperationLog( op.getId(), op.getBranch(), op.getWallClockTime(), op.getKeyspace(), op.getFromTimestamp(), op.getToTimestamp() ); } else if (datebackOperation instanceof TransformCommitOperation) { TransformCommitOperation op = (TransformCommitOperation) datebackOperation; return new TransformCommitOperationLog2( op.getId(), op.getBranch(), op.getWallClockTime(), op.getCommitTimestamp() ); } else if (datebackOperation instanceof TransformCommitOperation2) { TransformCommitOperation2 op = (TransformCommitOperation2) datebackOperation; return new TransformCommitOperationLog2( op.getId(), op.getBranch(), op.getWallClockTime(), op.getCommitTimestamp() ); } else if (datebackOperation instanceof TransformValuesOperation) { TransformValuesOperation op = (TransformValuesOperation) datebackOperation; return new TransformValuesOperationLog( op.getId(), op.getBranch(), op.getWallClockTime(), op.getKeyspace(), op.getKey(), op.getCommitTimestamps() ); } else if (datebackOperation instanceof UpdateCommitMetadataOperation) { UpdateCommitMetadataOperation op = (UpdateCommitMetadataOperation) datebackOperation; return new UpdateCommitMetadataOperationLog( op.getId(), op.getBranch(), op.getWallClockTime(), op.getCommitTimestamp() ); } else if(datebackOperation instanceof TransformValuesOfKeyspaceOperation){ TransformValuesOfKeyspaceOperation op = (TransformValuesOfKeyspaceOperation)datebackOperation; return new TransformValuesOfKeyspaceOperationLog( op.getId(), op.getBranch(), op.getWallClockTime(), op.getKeyspace(), op.getEarliestAffectedTimestamp() ); } else { throw new ChronoDBException("Failed to write dump for dateback operation of type '" + datebackOperation.getClass().getName() + "'!"); } } // ===================================================================================================================== // DESERIALIZATION / DUMP READ METHODS // ===================================================================================================================== public static ChronoDBDumpMetadata readMetadata(final ObjectInput input) { checkNotNull(input, "Precondition violation - argument 'input' must not be NULL!"); if (input.hasNext() == false) { throw new ChronoDBSerializationException("Failed to read dump - metadata entry is missing!"); } ChronoDBDumpElement element = (ChronoDBDumpElement) input.next(); if (element instanceof ChronoDBDumpMetadata == false) { throw new ChronoDBSerializationException("Failed to read dump - metadata entry is missing!"); } return (ChronoDBDumpMetadata) element; } public static void createBranches(final ChronoDBInternal db, final ChronoDBDumpMetadata metadata) { checkNotNull(db, "Precondition violation - argument 'db' must not be NULL!"); checkNotNull(metadata, "Precondition violation - argument 'metadata' must not be NULL!"); BranchManagerInternal branchManager = db.getBranchManager(); Set<BranchDumpMetadata> branchDumpMetadata = metadata.getBranchDumpMetadata(); // strategy note: // In order to achieve the loading of branch data, we need to feed the branches into // branchManager.loadBranchDataFromDump(...). However, the ordering matters in this case, // because we can only create a 'real' branch if the parent branch already exists in the // system. We therefore need to create a sorted list of branches such that the parent // branch is always loaded before the child branch. We do this by calculating a mapping // from parent to child branches, then recursively iterating over the structure using // a breadth-first-search, and insert the encountered branches into a list. BranchDumpMetadata masterDumpBranch = null; // branch name to sub-branches SetMultimap<String, BranchDumpMetadata> subBranches = HashMultimap.create(); // branch name to metadata Map<String, BranchDumpMetadata> branchByName = Maps.newHashMap(); for (BranchDumpMetadata branch : branchDumpMetadata) { if (branch.getParentName() == null) { // we have found the master branch if (branch.getName().equals(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER) == false) { // a branch without a parent that is not the master branch...? throw new IllegalStateException( "Found branch that has no parent, but is called '" + branch.getName() + "' (expected name: '" + ChronoDBConstants.MASTER_BRANCH_IDENTIFIER + "')!"); } if (masterDumpBranch != null) { // the master branch must be unique... how did this even happen? throw new IllegalStateException( "Found multiple branches without parent (only master branch may have no parent)! Encountered branches: '" + masterDumpBranch.getName() + "', '" + branch.getName() + "'"); } masterDumpBranch = branch; } else { // we are dealing with a regular branch subBranches.put(branch.getParentName(), branch); } // in any case, remember the branch by name in our map branchByName.put(branch.getName(), branch); } // convert to "real" branch objects IBranchMetadata master = IBranchMetadata.createMasterBranchMetadata(); List<IBranchMetadata> loadedBranches = Lists.newArrayList(); Stack<IBranchMetadata> branchesToVisit = new Stack<>(); // start the conversion at the master branch branchesToVisit.push(master); while (branchesToVisit.isEmpty() == false) { IBranchMetadata currentBranch = branchesToVisit.pop(); Set<BranchDumpMetadata> childDumpBranches = subBranches.get(currentBranch.getName()); for (BranchDumpMetadata childDumpBranch : childDumpBranches) { String childBranchName = childDumpBranch.getName(); long branchingTimestamp = childDumpBranch.getBranchingTimestamp(); String directoryName = null; if (childDumpBranch.getDirectoryName() == null) { if (db.isFileBased()) { if (childBranchName.equals(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER)) { directoryName = ChronoDBConstants.MASTER_BRANCH_IDENTIFIER; } else { directoryName = UUID.randomUUID().toString().replaceAll("-", "_"); } } } else { directoryName = childDumpBranch.getDirectoryName(); } // create the child IBranchMetadata childBranchMetadata = IBranchMetadata.create(childBranchName, currentBranch.getName(), branchingTimestamp, directoryName); // remember to visit this child to create its children branchesToVisit.push(childBranchMetadata); // remember that we created this child loadedBranches.add(childBranchMetadata); } } // load the branch data into the DB system branchManager.loadBranchDataFromDump(loadedBranches); } private static void loadEntries(final ChronoDBInternal db, final ObjectInput input, final ChronoDBDumpMetadata metadata, final ConverterRegistry converters, final DumpOptions options) { checkNotNull(db, "Precondition violation - argument 'db' must not be NULL!"); checkNotNull(input, "Precondition violation - argument 'input' must not be NULL!"); checkNotNull(metadata, "Precondition violation - argument 'metadata' must not be NULL!"); checkNotNull(converters, "Precondition violation - argument 'converters' must not be NULL!"); checkNotNull(options, "Precondition violation - argument 'options' must not be NULL!"); SerializationManager sm = db.getSerializationManager(); // this is our read batch. We fill it one by one, when it's full, we load that batch into the DB. List<ChronoDBEntry> readBatch = Lists.newArrayList(); int batchSize = options.getBatchSize(); // we also maintain a list of encountered commit timestamps. CommitMetadataMap commitMetadataMap = new CommitMetadataMap(); // copy over the commits we obtained from the commit metadata map (if any) List<CommitDumpMetadata> commitDumpMetadata = metadata.getCommitDumpMetadata(); for (CommitDumpMetadata commit : commitDumpMetadata) { commitMetadataMap.addEntry(commit.getBranch(), commit.getTimestamp(), commit.getMetadata()); } while (input.hasNext()) { ChronoDBDumpElement element = (ChronoDBDumpElement) input.next(); // this element should be an entry... if (element instanceof ChronoDBDumpEntry == false) { // hm... no idea what this could be. log.error("Encountered unexpected element of type '" + element.getClass().getName() + "', expected '" + ChronoDBDumpEntry.class.getName() + "'. Skipping this entry."); continue; } // cast down to the entry and check what it is ChronoDBDumpEntry<?> dumpEntry = (ChronoDBDumpEntry<?>) element; ChronoDBEntry entry = convertDumpEntryToDBEntry(dumpEntry, sm, converters); readBatch.add(entry); commitMetadataMap.addEntry(entry.getIdentifier()); // check if we need to flush our read batch into the DB if (readBatch.size() >= batchSize) { if (log.isDebugEnabled()) { log.debug("Reading a batch of size " + batchSize); } db.loadEntries(readBatch); readBatch.clear(); } } // we are at the end of the input; flush the remaining buffer (if any) if (readBatch.isEmpty() == false) { db.loadEntries(readBatch); readBatch.clear(); } // write the commit timestamps table db.loadCommitTimestamps(commitMetadataMap); } public static ChronoDBEntry convertDumpEntryToDBEntry(final ChronoDBDumpEntry<?> dumpEntry, final SerializationManager serializationManager, final ConverterRegistry converters) { checkNotNull(dumpEntry, "Precondition violation - argument 'dumpEntry' must not be NULL!"); checkNotNull(serializationManager, "Precondition violation - argument 'serializationManager' must not be NULL!"); checkNotNull(converters, "Precondition violation - argument 'converters' must not be NULL!"); try { if (dumpEntry instanceof ChronoDBDumpBinaryEntry) { return convertBinaryDumpEntryToDBEntry(dumpEntry); } else if (dumpEntry instanceof ChronoDBDumpPlainEntry) { return convertPlainTextDumpEntryToDBEntry(dumpEntry, serializationManager, converters); } else { // can this even happen? throw new IllegalArgumentException("Encountered unknown entry class: '" + dumpEntry.getClass().getName() + "'!"); } } catch (Exception e) { throw new ChronoDBStorageBackendException("Failed to read dump entry!", e); } } private static ChronoDBEntry convertBinaryDumpEntryToDBEntry(final ChronoDBDumpEntry<?> dumpEntry) { ChronoDBDumpBinaryEntry binaryEntry = (ChronoDBDumpBinaryEntry) dumpEntry; ChronoIdentifier identifier = binaryEntry.getChronoIdentifier(); byte[] value = binaryEntry.getValue(); return ChronoDBEntry.create(identifier, value); } @SuppressWarnings({"unchecked", "rawtypes"}) private static ChronoDBEntry convertPlainTextDumpEntryToDBEntry(final ChronoDBDumpEntry<?> dumpEntry, final SerializationManager serializationManager, final ConverterRegistry converters) throws Exception { ChronoDBDumpPlainEntry plainEntry = (ChronoDBDumpPlainEntry) dumpEntry; String converterClassName = plainEntry.getConverterClassName(); ChronoConverter<?, ?> converter = null; if (converterClassName != null) { // look for the explicit converter converter = converters.getConverterByClassName(converterClassName); if (converter == null) { throw new ChronoDBStorageBackendException("Failed to instantiate plain text converter '" + converterClassName + "'!"); } } if (converter == null) { // check if we have a default converter converter = converters.getConverterForObject(plainEntry.getValue()); } Object deserializedValue = null; if (converter != null) { // use the converter deserializedValue = ((ChronoConverter) converter).readFromInput(plainEntry.getValue()); } else { // well-known objects don't have/need a converter. deserializedValue = plainEntry.getValue(); } byte[] serializedValue = serializationManager.serialize(deserializedValue); return ChronoDBEntry.create(plainEntry.getChronoIdentifier(), serializedValue); } public static void setupIndexers(final ChronoDBInternal db, final ChronoDBDumpMetadata metadata) { checkNotNull(db, "Precondition violation - argument 'db' must not be NULL!"); checkNotNull(metadata, "Precondition violation - argument 'metadata' must not be NULL!"); IndexManagerInternal indexManager = db.getIndexManager(); Set<IIndexerDumpMetadata> indexerDumpMetadata = metadata.getIndexerDumpMetadata(); // insert the indexers, one by one Set<SecondaryIndex> indices = indexerDumpMetadata.stream().map(ChronoDBDumpUtil::loadIndexerFromDump).filter(Objects::nonNull).collect(Collectors.toSet()); indexManager.addIndices(indices); } private static SecondaryIndex loadIndexerFromDump(final IIndexerDumpMetadata indexerMetadata) { try { if (indexerMetadata instanceof IndexerDumpMetadata) { // Version 1 -> superseded by SecondaryIndex IndexerDumpMetadata indexerDump = (IndexerDumpMetadata) indexerMetadata; Indexer<?> indexer = indexerDump.getIndexer(); String indexName = indexerDump.getIndexName(); return new SecondaryIndexImpl( UUID.randomUUID().toString(), indexName, indexer, Period.eternal(), ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, null, /* parent index */ true, /* dirty */ Collections.emptySet() /* options */ ); } else if (indexerMetadata instanceof IndexerDumpMetadataV2) { return ((IndexerDumpMetadataV2) indexerMetadata).toSecondaryIndex(); } else { log.error("Failed to reconstruct an index because the dump class '" + indexerMetadata.getClass().getName() + "' is unknown" + " - skipping it!"); return null; } } catch (Exception e) { log.error("Failed to reconstruct an index because of a deserialization exception" + " - skipping it!", e); return null; } } public static void loadDatebackLog(final ChronoDBInternal db, final ChronoDBDumpMetadata metadata) { checkNotNull(db, "Precondition violation - argument 'db' must not be NULL!"); checkNotNull(metadata, "Precondition violation - argument 'metadata' must not be NULL!"); DatebackManagerInternal datebackManager = db.getDatebackManager(); metadata.getDatebackLog().stream() .map(ChronoDBDumpUtil::importDatebackOperation) .forEach(datebackManager::addDatebackOperationToLog); } private static DatebackOperation importDatebackOperation(DatebackLog operation) { checkNotNull(operation, "Precondition violation - argument 'operation' must not be NULL!"); if (operation instanceof InjectEntriesOperationLog) { InjectEntriesOperationLog op = (InjectEntriesOperationLog) operation; return new InjectEntriesOperation( op.getId(), op.getBranch(), op.getWallClockTime(), op.getOperationTimestamp(), op.getInjectedKeys(), op.isCommitMetadataOverride() ); } else if (operation instanceof PurgeCommitsOperationLog) { PurgeCommitsOperationLog op = (PurgeCommitsOperationLog) operation; return new PurgeCommitsOperation( op.getId(), op.getBranch(), op.getWallClockTime(), op.getCommitTimestamps() ); } else if (operation instanceof PurgeEntryOperationLog) { PurgeEntryOperationLog op = (PurgeEntryOperationLog) operation; return new PurgeEntryOperation( op.getId(), op.getBranch(), op.getWallClockTime(), op.getOperationTimestamp(), op.getKeyspace(), op.getKey() ); } else if (operation instanceof PurgeKeyOperationLog) { PurgeKeyOperationLog op = (PurgeKeyOperationLog) operation; return new PurgeKeyOperation( op.getId(), op.getBranch(), op.getWallClockTime(), op.getKeyspace(), op.getKey(), op.getFromTimestamp(), op.getToTimestamp() ); } else if (operation instanceof PurgeKeyspaceOperationLog) { PurgeKeyspaceOperationLog op = (PurgeKeyspaceOperationLog) operation; return new PurgeKeyspaceOperation( op.getId(), op.getBranch(), op.getWallClockTime(), op.getKeyspace(), op.getFromTimestamp(), op.getToTimestamp() ); } else if (operation instanceof TransformCommitOperationLog) { TransformCommitOperationLog op = (TransformCommitOperationLog) operation; return new TransformCommitOperation2( op.getId(), op.getBranch(), op.getWallClockTime(), op.getCommitTimestamp() ); } else if (operation instanceof TransformCommitOperationLog2) { TransformCommitOperationLog2 op = (TransformCommitOperationLog2) operation; return new TransformCommitOperation2( op.getId(), op.getBranch(), op.getWallClockTime(), op.getCommitTimestamp() ); } else if (operation instanceof TransformValuesOperationLog) { TransformValuesOperationLog op = (TransformValuesOperationLog) operation; return new TransformValuesOperation( op.getId(), op.getBranch(), op.getWallClockTime(), op.getKeyspace(), op.getKey(), op.getCommitTimestamps() ); } else if (operation instanceof UpdateCommitMetadataOperationLog) { UpdateCommitMetadataOperationLog op = (UpdateCommitMetadataOperationLog) operation; return new UpdateCommitMetadataOperation( op.getId(), op.getBranch(), op.getWallClockTime(), op.getCommitTimestamp() ); } else if(operation instanceof TransformValuesOfKeyspaceOperationLog){ TransformValuesOfKeyspaceOperationLog op = (TransformValuesOfKeyspaceOperationLog) operation; return new TransformValuesOfKeyspaceOperation( op.getId(), op.getBranch(), op.getWallClockTime(), op.getKeyspace(), op.getEarliestAffectedCommit() ); } else { throw new ChronoDBException("Failed to import dateback log operation of type '" + operation + "'!"); } } public static void setupIndexersAndReindex(final ChronoDBInternal db, final ChronoDBDumpMetadata metadata) { checkNotNull(db, "Precondition violation - argument 'db' must not be NULL!"); checkNotNull(metadata, "Precondition violation - argument 'metadata' must not be NULL!"); setupIndexers(db, metadata); // reconstruct the index db.getIndexManager().reindexAll(); } }
39,668
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
CommitMetadataMap.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dump/CommitMetadataMap.java
package org.chronos.chronodb.internal.impl.dump; import static com.google.common.base.Preconditions.*; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.SortedMap; import org.chronos.chronodb.api.key.ChronoIdentifier; import com.google.common.collect.Maps; public class CommitMetadataMap { /** Branch name -> commit timestamp -> commit metadata */ private final Map<String, SortedMap<Long, Object>> branchToCommitTimestamps; public CommitMetadataMap() { this.branchToCommitTimestamps = Maps.newHashMap(); } /** * Adds the given identifier to the commit timestamp map. * * <p> * It will have <code>null</code> associated as commit metadata. If a commit metadata object already exists for that timestamp, the metadata will be kept and will <b>not</b> be overwritten with <code>null</code>. * * @param identifier * The {@link ChronoIdentifier} to add to the commit map. Must not be <code>null</code>. */ public void addEntry(final ChronoIdentifier identifier) { checkNotNull(identifier, "Precondition violation - argument 'identifier' must not be NULL!"); this.addEntry(identifier.getBranchName(), identifier.getTimestamp(), null); } /** * Adds the given commit timestamp (and metadata) to this map. * * * @param branch * The name of the branch on which the commit occurred. Must not be <code>null</code>. * @param timestamp * The timestamp at which the commit occurred. Must not be negative. * @param metadata * The metadata associated with the branch. May be <code>null</code>. */ public void addEntry(final String branch, final long timestamp, final Object metadata) { checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); checkArgument(timestamp >= 0, "Precondition violation - argument 'branch' must not be negative!"); SortedMap<Long, Object> map = this.branchToCommitTimestamps.get(branch); if (map == null) { map = Maps.newTreeMap(); this.branchToCommitTimestamps.put(branch, map); } map.putIfAbsent(timestamp, metadata); } /** * Returns the set of branch names for which commits are available. * * @return Returns an unmodifiable view on the set of branches which have commits assigned to them in this map. Never <code>null</code>. */ public Set<String> getContainedBranches() { return Collections.unmodifiableSet(this.branchToCommitTimestamps.keySet()); } /** * Returns the commit timestamps (and associated metadata) for the given branch. * * <p> * The keys of the map are the commit timestamps, the values are the metadata associated with the commit (which may be <code>null</code>). * * @param branchName * The name of the branch to get the commits for. Must not be <code>null</code>. * @return An unmodifiable view on the map from timestamp to commit metadata for the given branch. May be empty, but never <code>null</code>. */ public SortedMap<Long, Object> getCommitMetadataForBranch(final String branchName) { checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!"); SortedMap<Long, Object> map = this.branchToCommitTimestamps.get(branchName); if (map == null) { map = Collections.emptySortedMap(); } return Collections.unmodifiableSortedMap(map); } }
3,360
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
DumpOptions.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dump/DumpOptions.java
package org.chronos.chronodb.internal.impl.dump; import static com.google.common.base.Preconditions.*; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.chronos.chronodb.api.DumpOption; import org.chronos.chronodb.api.DumpOption.IntOption; import com.google.common.collect.Sets; public class DumpOptions { // ===================================================================================================================== // DEFAULTS // ===================================================================================================================== public static final int DEFAULT_BATCH_SIZE = 1000; // ===================================================================================================================== // FIELDS // ===================================================================================================================== private final Set<DumpOption> options = Sets.newHashSet(); public DumpOptions(final DumpOption... options) { if (options != null && options.length > 0) { for (DumpOption option : options) { this.options.add(option); } } } public void enable(final DumpOption option) { checkNotNull(option, "Precondition violation - argument 'option' must not be NULL!"); this.options.add(option); } public void disable(final DumpOption option) { checkNotNull(option, "Precondition violation - argument 'option' must not be NULL!"); this.options.remove(option); } public boolean isGZipEnabled() { return this.isOptionEnabled(DumpOption.ENABLE_GZIP); } public boolean isForceBinaryEncodingEnabled() { return this.isOptionEnabled(DumpOption.FORCE_BINARY_ENCODING); } public boolean isOptionEnabled(final DumpOption option) { checkNotNull(option, "Precondition violation - argument 'option' must not be NULL!"); return this.options.contains(option); } public Set<DumpOption.AliasOption> getAliasOptions() { return this.options.stream() // filter only the alias options .filter(option -> option instanceof DumpOption.AliasOption) // cast them to the correct type .map(option -> (DumpOption.AliasOption) option) // collect them in a set .collect(Collectors.toSet()); } public Set<DumpOption.DefaultConverterOption> getDefaultConverterOptions() { return this.options.stream() // filter only the default converter options .filter(option -> option instanceof DumpOption.DefaultConverterOption) // cast them to the correct type .map(option -> (DumpOption.DefaultConverterOption) option) // collect them in a set .collect(Collectors.toSet()); } public int getBatchSize() { Optional<IntOption> batchSize = this.options.stream().filter(option -> option instanceof IntOption) .map(option -> (IntOption) option).filter(option -> "batchSize".equals(option.getName())).findAny(); if (batchSize.isPresent()) { return batchSize.get().getValue(); } else { return DEFAULT_BATCH_SIZE; } } public DumpOption[] toArray() { return this.options.toArray(new DumpOption[this.options.size()]); } }
3,110
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChunkDumpMetadata.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dump/incremental/ChunkDumpMetadata.java
package org.chronos.chronodb.internal.impl.dump.incremental; import com.google.common.collect.Lists; import org.chronos.chronodb.internal.api.Period; import org.chronos.chronodb.internal.impl.dump.meta.CommitDumpMetadata; import java.util.Collections; import java.util.List; import static com.google.common.base.Preconditions.*; public class ChunkDumpMetadata { // ================================================================================================================= // FIELDS // ================================================================================================================= private String branchName; private long chunkSequenceNumber; private long validFrom; private long validTo; private List<CommitDumpMetadata> commitMetadata; // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= protected ChunkDumpMetadata(){ // default constructor for (de-)serialization } public ChunkDumpMetadata(String branchName, long chunkSequenceNumber, Period validPeriod, List<CommitDumpMetadata> commitMetadata){ checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!"); checkArgument(chunkSequenceNumber >= 0, "Precondition violation - argument 'chunkSequenceNumber' must not be negative!"); checkNotNull(validPeriod, "Precondition violation - argument 'validPeriod' must not be NULL!"); checkNotNull(commitMetadata, "Precondition violation - argument 'commitMetadata' must not be NULL!"); this.branchName = branchName; this.chunkSequenceNumber = chunkSequenceNumber; this.validFrom = validPeriod.getLowerBound(); this.validTo = validPeriod.getUpperBound(); this.commitMetadata = Lists.newArrayList(commitMetadata); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= public String getBranchName() { return branchName; } public long getChunkSequenceNumber() { return chunkSequenceNumber; } public Period getValidPeriod(){ return Period.createRange(this.validFrom, this.validTo); } public List<CommitDumpMetadata> getCommitMetadata() { return Collections.unmodifiableList(commitMetadata); } }
2,667
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoDBDumpBinaryEntry.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dump/entry/ChronoDBDumpBinaryEntry.java
package org.chronos.chronodb.internal.impl.dump.entry; import java.util.Base64; import org.chronos.chronodb.api.key.ChronoIdentifier; public class ChronoDBDumpBinaryEntry extends ChronoDBDumpEntry<byte[]> { private String binaryValue; // ===================================================================================================================== // CONSTRUCTORS // ===================================================================================================================== protected ChronoDBDumpBinaryEntry() { // constructor for serialization purposes only } public ChronoDBDumpBinaryEntry(final ChronoIdentifier identifier, final byte[] value) { super(identifier); this.setValue(value); } // ===================================================================================================================== // GETTERS & SETTERS // ===================================================================================================================== @Override public void setValue(final byte[] value) { if (value == null) { this.binaryValue = null; } else { this.binaryValue = Base64.getEncoder().encodeToString(value); } } @Override public byte[] getValue() { if (this.binaryValue == null) { return null; } else { return Base64.getDecoder().decode(this.binaryValue); } } }
1,355
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoDBDumpPlainEntry.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dump/entry/ChronoDBDumpPlainEntry.java
package org.chronos.chronodb.internal.impl.dump.entry; import org.chronos.chronodb.api.dump.ChronoConverter; import org.chronos.chronodb.api.key.ChronoIdentifier; public class ChronoDBDumpPlainEntry extends ChronoDBDumpEntry<Object> { private Object value; private String converterClassName; // ===================================================================================================================== // CONSTRUCTORS // ===================================================================================================================== protected ChronoDBDumpPlainEntry() { // constructor for serialization purposes only } public ChronoDBDumpPlainEntry(final ChronoIdentifier identifier, final Object value, final ChronoConverter<?, ?> converter) { super(identifier); this.setValue(value); if (converter != null) { this.converterClassName = converter.getClass().getName(); } else { // this happens if we are dealing with a well-known object that needs no converter. this.converterClassName = null; } } // ===================================================================================================================== // GETTERS & SETTERS // ===================================================================================================================== @Override public void setValue(final Object value) { this.value = value; } @Override public Object getValue() { return this.value; } public String getConverterClassName() { return this.converterClassName; } public void setConverterClassName(final String converterClassName) { this.converterClassName = converterClassName; } }
1,670
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoDBDumpEntry.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dump/entry/ChronoDBDumpEntry.java
package org.chronos.chronodb.internal.impl.dump.entry; import org.chronos.chronodb.api.key.ChronoIdentifier; import org.chronos.chronodb.internal.impl.dump.base.ChronoDBDumpElement; public abstract class ChronoDBDumpEntry<T> extends ChronoDBDumpElement { private long timestamp; private String branch; private String keyspace; private String key; // ===================================================================================================================== // CONSTRUCTOR // ===================================================================================================================== public ChronoDBDumpEntry() { // serialization constructor this.timestamp = -1L; } public ChronoDBDumpEntry(final ChronoIdentifier identifier) { this.setChronoIdentifier(identifier); } // ===================================================================================================================== // GETTERS & SETTERS // ===================================================================================================================== public void setChronoIdentifier(final ChronoIdentifier identifier) { if (identifier == null) { // reset the identifier data this.timestamp = -1L; this.branch = null; this.keyspace = null; this.key = null; } else { // extract the data from the identifier this.timestamp = identifier.getTimestamp(); this.branch = identifier.getBranchName(); this.keyspace = identifier.getKeyspace(); this.key = identifier.getKey(); } } public ChronoIdentifier getChronoIdentifier() { if (this.timestamp < 0 || this.branch == null || this.keyspace == null || this.key == null) { // identifier was not set yet return null; } return ChronoIdentifier.create(this.branch, this.timestamp, this.keyspace, this.key); } public abstract T getValue(); public abstract void setValue(T value); }
1,901
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoDBDump.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dump/base/ChronoDBDump.java
package org.chronos.chronodb.internal.impl.dump.base; import org.chronos.chronodb.internal.impl.dump.entry.ChronoDBDumpEntry; import org.chronos.chronodb.internal.impl.dump.meta.ChronoDBDumpMetadata; public interface ChronoDBDump extends Iterable<ChronoDBDumpEntry<?>>, AutoCloseable { public ChronoDBDumpMetadata getDumpMetadata(); @Override public void close(); }
374
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
IndexerDumpMetadataV2.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dump/meta/IndexerDumpMetadataV2.java
package org.chronos.chronodb.internal.impl.dump.meta; import org.chronos.chronodb.api.SecondaryIndex; import org.chronos.chronodb.api.indexing.Indexer; import org.chronos.chronodb.internal.api.Period; import org.chronos.chronodb.internal.impl.index.SecondaryIndexImpl; import org.chronos.common.serialization.KryoManager; import java.util.Base64; import java.util.Collections; public class IndexerDumpMetadataV2 implements IIndexerDumpMetadata { private String id; private String indexName; private String indexerData; private String branch; private Long validFrom; private Long validTo; private String parentIndexId; protected IndexerDumpMetadataV2() { } public IndexerDumpMetadataV2(SecondaryIndex index) { this.id = index.getId(); this.indexName = index.getName(); byte[] indexerSerialized = KryoManager.serialize(index.getIndexer()); this.indexerData = Base64.getEncoder().encodeToString(indexerSerialized); this.branch = index.getBranch(); this.validFrom = index.getValidPeriod().getLowerBound(); this.validTo = index.getValidPeriod().getUpperBound(); this.parentIndexId = index.getParentIndexId(); } public SecondaryIndex toSecondaryIndex() { byte[] serialForm = Base64.getDecoder().decode(this.indexerData); Indexer<?> indexer = KryoManager.deserialize(serialForm); return new SecondaryIndexImpl( id, indexName, indexer, Period.createRange(validFrom, validTo), branch, parentIndexId, true, Collections.emptySet() ); } }
1,679
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
CommitDumpMetadata.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dump/meta/CommitDumpMetadata.java
package org.chronos.chronodb.internal.impl.dump.meta; import static com.google.common.base.Preconditions.*; public class CommitDumpMetadata { // ================================================================================================================= // FIELDS // ================================================================================================================= private long timestamp; private String branch; private Object metadata; // ================================================================================================================= // CONSTRUCTORS // ================================================================================================================= public CommitDumpMetadata() { // default constructor for (de-)serialization } public CommitDumpMetadata(final String branch, final long timestamp, final Object metadata) { checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); this.branch = branch; this.timestamp = timestamp; this.metadata = metadata; } // ================================================================================================================= // GETTERS & SETTERS // ================================================================================================================= public long getTimestamp() { return this.timestamp; } public String getBranch() { return this.branch; } public Object getMetadata() { return this.metadata; } }
1,613
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoDBDumpMetadata.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dump/meta/ChronoDBDumpMetadata.java
package org.chronos.chronodb.internal.impl.dump.meta; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.chronos.chronodb.internal.impl.dump.base.ChronoDBDumpElement; import org.chronos.chronodb.internal.impl.dump.meta.dateback.DatebackLog; import org.chronos.common.version.ChronosVersion; import java.util.Date; import java.util.List; import java.util.Set; public class ChronoDBDumpMetadata extends ChronoDBDumpElement { // ===================================================================================================================== // FIELDS // ===================================================================================================================== /** * The date (and time) at which this element was created. */ private Date creationDate; /** * The version of Chronos that created this element. */ private String chronosVersion; /** * The metadata associated with each commit. * * @since 0.6.1 */ private List<CommitDumpMetadata> commitMetadata = Lists.newArrayList(); /** * The metetadata associated to each branch. */ private Set<BranchDumpMetadata> branchMetadata = Sets.newHashSet(); /** * The indexers and corresponding metadata. */ private Set<IIndexerDumpMetadata> indexerMetadata = Sets.newHashSet(); /** * The dateback operation log. */ private Set<DatebackLog> datebackLog = Sets.newHashSet(); // ===================================================================================================================== // CONSTRUCTOR // ===================================================================================================================== public ChronoDBDumpMetadata() { // default constructor, also needed for serialization } // ===================================================================================================================== // GETTERS & SETTERS // ===================================================================================================================== public void setChronosVersion(final ChronosVersion version) { if (version == null) { this.chronosVersion = null; return; } this.chronosVersion = version.toString(); } public ChronosVersion getChronosVersion() { if (this.chronosVersion == null) { return null; } return ChronosVersion.parse(this.chronosVersion); } public void setCreationDate(final Date date) { if (date == null) { this.creationDate = null; return; } this.creationDate = new Date(date.getTime()); } public Date getCreationDate() { if (this.creationDate == null) { return null; } return new Date(this.creationDate.getTime()); } public Set<BranchDumpMetadata> getBranchDumpMetadata() { return this.branchMetadata; } public Set<IIndexerDumpMetadata> getIndexerDumpMetadata() { return this.indexerMetadata; } public Set<DatebackLog> getDatebackLog(){ if(this.datebackLog == null){ // some dumps maybe do not contain this data, and // deserializers might assign NULL to the field. Just // to be safe, let's re-initialize the list in this case. this.datebackLog = Sets.newHashSet(); } return this.datebackLog; } /** * Returns the commit metadata stored in this dump. * * <p> * The returned list is the internal representation; modifications to this list will be visible in the owning object! * * @return The list of commit metadata entries. * @since 0.6.1 */ public List<CommitDumpMetadata> getCommitDumpMetadata() { if (this.commitMetadata == null) { // some dumps maybe do not contain this data, and // deserializers might assing NULL to the field. Just // to be safe, let's re-initialize the list in this case. this.commitMetadata = Lists.newArrayList(); } return this.commitMetadata; } }
4,252
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
BranchDumpMetadata.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dump/meta/BranchDumpMetadata.java
package org.chronos.chronodb.internal.impl.dump.meta; import static com.google.common.base.Preconditions.*; import org.chronos.chronodb.api.Branch; import org.chronos.chronodb.api.ChronoDBConstants; public class BranchDumpMetadata { public static BranchDumpMetadata createMasterBranchMetadata() { BranchDumpMetadata metadata = new BranchDumpMetadata(); metadata.name = ChronoDBConstants.MASTER_BRANCH_IDENTIFIER; metadata.branchingTimestamp = 0L; metadata.parentName = null; return metadata; } // ===================================================================================================================== // FIELDS // ===================================================================================================================== private String name; private String parentName; private long branchingTimestamp; private String directoryName; // ===================================================================================================================== // CONSTRUCTORS // ===================================================================================================================== public BranchDumpMetadata() { // serialization constructor } public BranchDumpMetadata(final Branch branch) { checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); this.name = branch.getName(); if (branch.getOrigin() != null) { this.parentName = branch.getOrigin().getName(); } else { this.parentName = null; } this.branchingTimestamp = branch.getBranchingTimestamp(); this.directoryName = branch.getDirectoryName(); } // ===================================================================================================================== // GETTERS & SETTERS // ===================================================================================================================== public String getName() { return this.name; } public String getParentName() { return this.parentName; } public long getBranchingTimestamp() { return this.branchingTimestamp; } public String getDirectoryName(){ return this.directoryName; } @Override public String toString() { return "BranchDumpMetadata[" +this.name + ", parent=" + this.parentName + ", branchingTimestamp=" + branchingTimestamp + ", dirName=" + directoryName + "]"; } }
2,354
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
IndexerDumpMetadata.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dump/meta/IndexerDumpMetadata.java
package org.chronos.chronodb.internal.impl.dump.meta; import java.util.Base64; import org.chronos.chronodb.api.indexing.Indexer; import org.chronos.common.serialization.KryoManager; public class IndexerDumpMetadata implements IIndexerDumpMetadata { private String indexName; private String indexerData; public IndexerDumpMetadata() { // serialization constructor } public IndexerDumpMetadata(final String indexName, final Indexer<?> indexer) { this.setIndexName(indexName); this.setIndexer(indexer); } // ===================================================================================================================== // PUBLIC API // ===================================================================================================================== public void setIndexName(final String indexName) { this.indexName = indexName; } public String getIndexName() { return this.indexName; } public void setIndexer(final Indexer<?> indexer) { if (indexer == null) { this.indexerData = null; } else { byte[] serialForm = KryoManager.serialize(indexer); this.indexerData = Base64.getEncoder().encodeToString(serialForm); } } public Indexer<?> getIndexer() { if (this.indexerData == null) { return null; } else { byte[] serialForm = Base64.getDecoder().decode(this.indexerData); return KryoManager.deserialize(serialForm); } } }
1,398
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
SchemaValidatorMetadata.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dump/meta/SchemaValidatorMetadata.java
package org.chronos.chronodb.internal.impl.dump.meta; public class SchemaValidatorMetadata { private String validatorName; private String validatorScriptContent; public SchemaValidatorMetadata() { } public SchemaValidatorMetadata(String validatorName, String validatorScriptContent) { this.validatorName = validatorName; this.validatorScriptContent = validatorScriptContent; } public String getValidatorName() { return validatorName; } public void setValidatorName(final String validatorName) { this.validatorName = validatorName; } public String getValidatorScriptContent() { return validatorScriptContent; } public void setValidatorScriptContent(final String validatorScriptContent) { this.validatorScriptContent = validatorScriptContent; } }
858
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
TransformValuesOfKeyspaceOperationLog.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dump/meta/dateback/TransformValuesOfKeyspaceOperationLog.java
package org.chronos.chronodb.internal.impl.dump.meta.dateback; import com.thoughtworks.xstream.annotations.XStreamAlias; import static com.google.common.base.Preconditions.*; @XStreamAlias("TransformValuesOfKeyspaceOperation") public class TransformValuesOfKeyspaceOperationLog extends DatebackLog { // ================================================================================================================= // FIELDS // ================================================================================================================= private String keyspace; private long earliestAffectedCommit; // ================================================================================================================= // CONSTRUCTORS // ================================================================================================================= protected TransformValuesOfKeyspaceOperationLog() { // default constructor for (de-)serialization } public TransformValuesOfKeyspaceOperationLog(String id, String branch, long wallClockTime, String keyspace, long earliestAffectedCommit) { super(id, branch, wallClockTime); checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkArgument(earliestAffectedCommit > 0, "Precondition violation - argument 'earliestAffectedCommit' must not be negative!"); this.keyspace = keyspace; this.earliestAffectedCommit = earliestAffectedCommit; } // ================================================================================================================= // PUBLIC API // ================================================================================================================= public long getEarliestAffectedCommit() { return earliestAffectedCommit; } public String getKeyspace() { return keyspace; } @Override public String toString() { return "TransformValuesOfKeyspace[target: " + this.getBranch() + ", keyspace: " + this.keyspace + ", earliest affected commit: " + this.earliestAffectedCommit + "]"; } }
2,228
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
InjectEntriesOperationLog.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dump/meta/dateback/InjectEntriesOperationLog.java
package org.chronos.chronodb.internal.impl.dump.meta.dateback; import com.google.common.collect.Sets; import com.thoughtworks.xstream.annotations.XStreamAlias; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.internal.impl.dateback.log.AbstractDatebackOperation; import java.util.Collections; import java.util.Set; import static com.google.common.base.Preconditions.*; @XStreamAlias("InjectEntriesOperation") public class InjectEntriesOperationLog extends DatebackLog { // ================================================================================================================= // FIELDS // ================================================================================================================= private long operationTimestamp; private boolean commitMetadataOverride; private Set<QualifiedKey> injectedKeys = Collections.emptySet(); // ================================================================================================================= // CONSTRUCTORS // ================================================================================================================= protected InjectEntriesOperationLog(){ // default constructor for (de-)serialization } public InjectEntriesOperationLog(String id, String branch, long wallClockTime, long timestamp, Set<QualifiedKey> injectedKeys, boolean commitMetadataOverride){ super(id, branch, wallClockTime); checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); checkNotNull(injectedKeys, "Precondition violation - argument 'injectedKeys' must not be NULL!"); this.operationTimestamp = timestamp; this.commitMetadataOverride = commitMetadataOverride; this.injectedKeys = Sets.newHashSet(injectedKeys); } // ================================================================================================================= // PUBCIC API // ================================================================================================================= public long getOperationTimestamp() { return this.operationTimestamp; } public boolean isCommitMetadataOverride() { return commitMetadataOverride; } public Set<QualifiedKey> getInjectedKeys() { return Collections.unmodifiableSet(injectedKeys); } @Override public String toString() { return "InjectEntries[target: " + this.getBranch() + "@" + this.getOperationTimestamp() + ", wallClockTime: " + this.getWallClockTime() + ", injectedKeys: " + this.getInjectedKeys().size() + "]"; } }
2,689
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
TransformCommitOperationLog.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dump/meta/dateback/TransformCommitOperationLog.java
package org.chronos.chronodb.internal.impl.dump.meta.dateback; import com.google.common.collect.Sets; import com.thoughtworks.xstream.annotations.XStreamAlias; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.internal.impl.dateback.log.AbstractDatebackOperation; import org.chronos.chronodb.internal.impl.dateback.log.v2.TransformCommitOperation2; import java.util.Collections; import java.util.Set; import static com.google.common.base.Preconditions.*; /** * This class has been deprecated in favour of the newer version {@link TransformCommitOperationLog2}. * * <p> * We still keep it here for backwards compatibility / deserialization purposes. * </p> */ @Deprecated @XStreamAlias("TransformCommitOperation") public class TransformCommitOperationLog extends DatebackLog { // ================================================================================================================= // FIELDS // ================================================================================================================= private long commitTimestamp; private Set<QualifiedKey> changedKeys; // ================================================================================================================= // CONSTRUCTORS // ================================================================================================================= protected TransformCommitOperationLog(){ // default constructor for (de-)serialization } public TransformCommitOperationLog(String id, String branch, long wallClockTime, long commitTimestamp, Set<QualifiedKey> changedKeys) { super(id, branch, wallClockTime); checkArgument(commitTimestamp >= 0, "Precondition violation - argument 'commitTimestamp' must not be negative!"); checkNotNull(changedKeys, "Precondition violation - argument 'changedKeys' must not be NULL!"); this.commitTimestamp = commitTimestamp; this.changedKeys = Sets.newHashSet(changedKeys); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= public long getCommitTimestamp() { return commitTimestamp; } public Set<QualifiedKey> getChangedKeys() { return Collections.unmodifiableSet(changedKeys); } @Override public String toString() { return "TransformCommit[target: " + this.getBranch() + "@" + this.getCommitTimestamp() + ", wallClockTime: " + this.getWallClockTime() + ", changedKeys: " + this.changedKeys.size() + "]"; } }
2,739
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
TransformValuesOperationLog.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dump/meta/dateback/TransformValuesOperationLog.java
package org.chronos.chronodb.internal.impl.dump.meta.dateback; import com.google.common.collect.Sets; import com.thoughtworks.xstream.annotations.XStreamAlias; import org.chronos.chronodb.internal.api.Period; import java.util.Collections; import java.util.Set; import static com.google.common.base.Preconditions.*; @XStreamAlias("TransformValuesOperation") public class TransformValuesOperationLog extends DatebackLog { // ================================================================================================================= // FIELDS // ================================================================================================================= private Set<Long> commitTimestamps; private String keyspace; private String key; // ================================================================================================================= // CONSTRUCTORS // ================================================================================================================= protected TransformValuesOperationLog() { // default constructor for (de-)serialization } public TransformValuesOperationLog(String id, String branch, long wallClockTime, String keyspace, String key, Set<Long> commitTimestamps) { super(id, branch, wallClockTime); checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); checkNotNull(commitTimestamps, "Precondition violation - argument 'commitTimestamps' must not be NULL!"); checkArgument(commitTimestamps.stream().anyMatch(t -> t < 0), "Precondition violation - none of the provided 'commitTimestamps' must be negative!"); this.keyspace = keyspace; this.key = key; this.commitTimestamps = Sets.newHashSet(commitTimestamps); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= public Set<Long> getCommitTimestamps() { return Collections.unmodifiableSet(commitTimestamps); } public String getKeyspace() { return keyspace; } public String getKey() { return key; } @Override public String toString() { long min = this.commitTimestamps.stream().mapToLong(l -> l).min().orElseThrow(IllegalStateException::new); long max = this.commitTimestamps.stream().mapToLong(l -> l).max().orElseThrow(IllegalStateException::new); if (max < Long.MAX_VALUE) { max += 1; // ranges render upper bound as exclusive, but our internal notation is inclusive } return "TransformValues[target: " + this.getBranch() + ", key: " + this.keyspace + "->" + this.key + " in " + this.commitTimestamps.size() + " timestamps in range " + Period.createRange(min, max) + "]"; } }
3,062
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
DatebackLog.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dump/meta/dateback/DatebackLog.java
package org.chronos.chronodb.internal.impl.dump.meta.dateback; import static com.google.common.base.Preconditions.*; public abstract class DatebackLog { // ================================================================================================================= // FIELDS // ================================================================================================================= private String id; private long wallClockTime; private String branch; // ================================================================================================================= // CONSTRUCTORS // ================================================================================================================= protected DatebackLog(){ // default constructor for (de-)serialization } protected DatebackLog(String id, String branch, long wallClockTime){ checkNotNull(id, "Precondition violation - argument 'id' must not be NULL!"); checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); checkArgument(wallClockTime >= 0, "Precondition violation - argument 'wallClockTime' must not be negative!"); this.id = id; this.branch = branch; this.wallClockTime = wallClockTime; } // ================================================================================================================= // PUBLIC API // ================================================================================================================= public String getId(){ return this.id; } public long getWallClockTime() { return this.wallClockTime; } public String getBranch() { return this.branch; } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DatebackLog that = (DatebackLog) o; return id != null ? id.equals(that.id) : that.id == null; } @Override public int hashCode() { return id != null ? id.hashCode() : 0; } }
2,189
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
PurgeEntryOperationLog.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dump/meta/dateback/PurgeEntryOperationLog.java
package org.chronos.chronodb.internal.impl.dump.meta.dateback; import com.thoughtworks.xstream.annotations.XStreamAlias; import static com.google.common.base.Preconditions.*; @XStreamAlias("PurgeEntryOperation") public class PurgeEntryOperationLog extends DatebackLog { // ================================================================================================================= // FIELDS // ================================================================================================================= private long operationTimestamp; private String keyspace; private String key; // ================================================================================================================= // CONSTRUCTORS // ================================================================================================================= protected PurgeEntryOperationLog(){ // default constructor for (de-)serialization } public PurgeEntryOperationLog(String id, String branch, long wallClockTime, long operationTimestamp, String keyspace, String key){ super(id, branch, wallClockTime); checkArgument(operationTimestamp >= 0, "Precondition violation - argument 'operationTimestamp' must not be negative!"); checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); this.keyspace = keyspace; this.key = key; this.operationTimestamp = operationTimestamp; } // ================================================================================================================= // PUBLIC API // ================================================================================================================= public String getKey() { return key; } public String getKeyspace() { return keyspace; } public long getOperationTimestamp() { return operationTimestamp; } @Override public String toString() { return "PurgeEntry[target: " + this.getBranch() + "@" + this.getOperationTimestamp() + ", wallClockTime: " + this.getWallClockTime() + ", purgedEntry: " + this.keyspace + "->" + this.key + "]"; } }
2,318
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
PurgeKeyOperationLog.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dump/meta/dateback/PurgeKeyOperationLog.java
package org.chronos.chronodb.internal.impl.dump.meta.dateback; import com.thoughtworks.xstream.annotations.XStreamAlias; import org.chronos.chronodb.internal.api.Period; import org.chronos.chronodb.internal.impl.dateback.log.AbstractDatebackOperation; import static com.google.common.base.Preconditions.*; @XStreamAlias("PurgeKeyOperation") public class PurgeKeyOperationLog extends DatebackLog { // ================================================================================================================= // FIELDS // ================================================================================================================= private String keyspace; private String key; private long fromTimestamp; private long toTimestamp; // ================================================================================================================= // CONSTRUCTORS // ================================================================================================================= public PurgeKeyOperationLog(){ // default constructor for (de-)serialization } public PurgeKeyOperationLog(String id, String branch, long wallClockTime, String keyspace, String key, long fromTimestamp, long toTimestamp){ super(id, branch, wallClockTime); checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); checkArgument(fromTimestamp >= 0, "Precondition violation - argument 'fromTimestamp' must not be negative!"); checkArgument(toTimestamp >= 0, "Precondition violation - argument 'toTimestamp' must not be negative!"); this.keyspace = keyspace; this.key = key; this.fromTimestamp = fromTimestamp; this.toTimestamp = toTimestamp; } // ================================================================================================================= // PUBLIC API // ================================================================================================================= public String getKeyspace() { return keyspace; } public String getKey() { return key; } public long getFromTimestamp() { return fromTimestamp; } public long getToTimestamp() { return toTimestamp; } @Override public String toString() { return "PurgeKey[branch: " + this.getBranch() + ", wallClockTime: " + this.getWallClockTime() + ", purged: " + this.keyspace + "->" + this.key + ", period: " + Period.createRange(this.fromTimestamp, this.toTimestamp+1) + "]"; } }
2,702
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
PurgeKeyspaceOperationLog.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dump/meta/dateback/PurgeKeyspaceOperationLog.java
package org.chronos.chronodb.internal.impl.dump.meta.dateback; import static com.google.common.base.Preconditions.*; public class PurgeKeyspaceOperationLog extends DatebackLog { // ================================================================================================================= // FIELDS // ================================================================================================================= private String keyspace; private long fromTimestamp; private long toTimestamp; // ================================================================================================================= // CONSTRUCTORS // ================================================================================================================= public PurgeKeyspaceOperationLog(){ // default constructor for (de-)serialization } public PurgeKeyspaceOperationLog(String id, String branch, long wallClockTime, String keyspace, long fromTimestamp, long toTimestamp){ super(id, branch, wallClockTime); checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkArgument(fromTimestamp >= 0, "Precondition violation - argument 'fromTimestamp' must not be negative!"); checkArgument(toTimestamp >= 0, "Precondition violation - argument 'toTimestamp' must not be negative!"); this.keyspace = keyspace; this.fromTimestamp = fromTimestamp; this.toTimestamp = toTimestamp; } // ================================================================================================================= // PUBLIC API // ================================================================================================================= public String getKeyspace() { return keyspace; } public long getFromTimestamp() { return fromTimestamp; } public long getToTimestamp() { return toTimestamp; } @Override public String toString() { final StringBuilder sb = new StringBuilder("PurgeKeyspaceOperationLog{"); sb.append("keyspace='").append(keyspace).append('\''); sb.append(", fromTimestamp=").append(fromTimestamp); sb.append(", toTimestamp=").append(toTimestamp); sb.append('}'); return sb.toString(); } }
2,371
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
TransformCommitOperationLog2.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dump/meta/dateback/TransformCommitOperationLog2.java
package org.chronos.chronodb.internal.impl.dump.meta.dateback; import com.thoughtworks.xstream.annotations.XStreamAlias; import static com.google.common.base.Preconditions.*; @XStreamAlias("TransformCommitOperation2") public class TransformCommitOperationLog2 extends DatebackLog { // ================================================================================================================= // FIELDS // ================================================================================================================= private long commitTimestamp; // ================================================================================================================= // CONSTRUCTORS // ================================================================================================================= protected TransformCommitOperationLog2(){ // default constructor for (de-)serialization } public TransformCommitOperationLog2(String id, String branch, long wallClockTime, long commitTimestamp) { super(id, branch, wallClockTime); checkArgument(commitTimestamp >= 0, "Precondition violation - argument 'commitTimestamp' must not be negative!"); this.commitTimestamp = commitTimestamp; } // ================================================================================================================= // PUBLIC API // ================================================================================================================= public long getCommitTimestamp() { return commitTimestamp; } @Override public String toString() { return "TransformCommit[target: " + this.getBranch() + "@" + this.getCommitTimestamp() + ", wallClockTime: " + this.getWallClockTime() + "]"; } }
1,819
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
UpdateCommitMetadataOperationLog.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dump/meta/dateback/UpdateCommitMetadataOperationLog.java
package org.chronos.chronodb.internal.impl.dump.meta.dateback; import com.thoughtworks.xstream.annotations.XStreamAlias; @XStreamAlias("UpdateCommitMetadataOperation") public class UpdateCommitMetadataOperationLog extends DatebackLog { // ================================================================================================================= // FIELDS // ================================================================================================================= private long commitTimestamp; // ================================================================================================================= // CONSTRUCTORS // ================================================================================================================= protected UpdateCommitMetadataOperationLog(){ // default constructor for (de-)serialization } public UpdateCommitMetadataOperationLog(String id, String branch, long wallClockTime, long commitTimestamp){ super(id, branch, wallClockTime); this.commitTimestamp = commitTimestamp; } // ================================================================================================================= // PUBLIC API // ================================================================================================================= public long getCommitTimestamp() { return commitTimestamp; } @Override public String toString() { return "UpdateCommitMetadata[target: " + this.getBranch() + "@" + this.commitTimestamp + ", wallClockTime: " + this.getWallClockTime() + "]"; } }
1,658
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
PurgeCommitsOperationLog.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/dump/meta/dateback/PurgeCommitsOperationLog.java
package org.chronos.chronodb.internal.impl.dump.meta.dateback; import com.google.common.collect.Sets; import com.thoughtworks.xstream.annotations.XStreamAlias; import org.chronos.chronodb.internal.impl.dateback.log.AbstractDatebackOperation; import java.util.Collections; import java.util.Set; import static com.google.common.base.Preconditions.*; @XStreamAlias("PurgecommitsOperation") public class PurgeCommitsOperationLog extends DatebackLog { // ================================================================================================================= // FIELDS // ================================================================================================================= private Set<Long> commitTimestamps; // ================================================================================================================= // CONSTRUCTORS // ================================================================================================================= protected PurgeCommitsOperationLog(){ // default constructor for (de-)serialization } public PurgeCommitsOperationLog(String id, String branch, long wallClockTime, Set<Long> commitTimestamps){ super(id, branch, wallClockTime); checkNotNull(commitTimestamps, "Precondition violation - argument 'commitTimestamps' must not be NULL!"); commitTimestamps.forEach(t -> checkArgument(t >= 0, "Precondition violation - argument 'commitTimestamps' must not contain negative values!")); this.commitTimestamps = Sets.newHashSet(commitTimestamps); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= public Set<Long> getCommitTimestamps() { return Collections.unmodifiableSet(this.commitTimestamps); } @Override public String toString() { return "PurgeCommits[branch: " + this.getBranch() + ", wallClockTime: " + this.getWallClockTime() + ", timestamps: " + this.commitTimestamps+ "]"; } }
2,198
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
TemporalKeyValueStoreBase.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/engines/base/TemporalKeyValueStoreBase.java
package org.chronos.chronodb.internal.impl.engines.base; import static com.google.common.base.Preconditions.*; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.builder.transaction.ChronoDBTransactionBuilder; import org.chronos.chronodb.api.exceptions.ChronoDBTransactionException; import org.chronos.chronodb.api.exceptions.InvalidTransactionBranchException; import org.chronos.chronodb.api.exceptions.InvalidTransactionTimestampException; import org.chronos.chronodb.internal.api.MutableTransactionConfiguration; import org.chronos.chronodb.internal.api.TemporalKeyValueStore; import org.chronos.chronodb.internal.api.TransactionConfigurationInternal; import org.chronos.chronodb.internal.impl.DefaultTransactionConfiguration; import org.chronos.chronodb.internal.util.ThreadBound; import org.chronos.common.autolock.AbstractAutoLock; import org.chronos.common.autolock.AutoLock; public abstract class TemporalKeyValueStoreBase implements TemporalKeyValueStore { // ===================================================================================================================== // FIELDS // ===================================================================================================================== /** * The branch lock protects a single branch from illegal concurrent access. * <p> * The vast majority of requests will only require a read lock, including (but not limited to): * <ul> * <li>Read operations * <li>Commits * </ul> * * An example for a process which does indeed require the write lock (i.e. exclusive lock) is a re-indexing process, * as index values will be invalid during this process, which makes reads pointless. * * <p> * Please note that acquiring any lock (read or write) on a branch is legal if and only if the currrent thread holds * a read lock on the owning database as well. */ private final ReadWriteLock branchLock = new ReentrantReadWriteLock(true); private final ThreadBound<AutoLock> nonExclusiveLockHolder = ThreadBound.createWeakReference(); private final ThreadBound<AutoLock> exclusiveLockHolder = ThreadBound.createWeakReference(); private final ThreadBound<AutoLock> branchExclusiveLockHolder = ThreadBound.createWeakReference(); // ================================================================================================================= // BRANCH LOCKING // ================================================================================================================= @Override public AutoLock lockNonExclusive() { AutoLock lockHolder = this.nonExclusiveLockHolder.get(); if (lockHolder == null) { lockHolder = new NonExclusiveAutoLock(); this.nonExclusiveLockHolder.set(lockHolder); } lockHolder.acquireLock(); return lockHolder; } @Override public AutoLock lockBranchExclusive() { AutoLock lockHolder = this.branchExclusiveLockHolder.get(); if (lockHolder == null) { lockHolder = new BranchExclusiveAutoLock(); this.branchExclusiveLockHolder.set(lockHolder); } lockHolder.acquireLock(); return lockHolder; } @Override public AutoLock lockExclusive() { AutoLock lockHolder = this.exclusiveLockHolder.get(); if (lockHolder == null) { lockHolder = new ExclusiveAutoLock(); this.exclusiveLockHolder.set(lockHolder); } lockHolder.acquireLock(); return lockHolder; } // ================================================================================================================= // OPERATION [ TX ] // ================================================================================================================= @Override public ChronoDBTransactionBuilder txBuilder() { return this.getOwningDB().txBuilder().onBranch(this.getOwningBranch()); } @Override public ChronoDBTransaction tx(final TransactionConfigurationInternal configuration) { checkNotNull(configuration, "Precondition violation - argument 'configuration' must not be NULL!"); try (AutoLock lock = this.lockNonExclusive()) { String branchName = configuration.getBranch(); long timestamp; if (configuration.isTimestampNow()) { timestamp = this.getNow(); } else { timestamp = configuration.getTimestamp(); } if (timestamp > this.getNow()) { throw new InvalidTransactionTimestampException( "Cannot open transaction at the given date or timestamp: it's after the latest commit! Branch Identifier: " + branchName); } if (branchName.equals(this.getOwningBranch().getName()) == false) { throw new InvalidTransactionBranchException("Cannot start transaction on branch '" + this.getOwningBranch().getName() + "' when transaction configuration specifies branch '" + configuration.getBranch() + "'!"); } if (configuration.isThreadSafe()) { return new ThreadSafeChronoDBTransaction(this, timestamp, branchName, configuration); } else { return new StandardChronoDBTransaction(this, timestamp, branchName, configuration); } } } @Override public ChronoDBTransaction txInternal(final String branch, final long timestamp) { checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); MutableTransactionConfiguration configuration = new DefaultTransactionConfiguration(); configuration.setTimestamp(timestamp); configuration.setBranch(branch); return new StandardChronoDBTransaction(this, timestamp, branch, configuration); } // ================================================================================================================= // ABSTRACT METHODS // ================================================================================================================= /** * Verification method for implementations of this class. * * <p> * The implementing method can perform arbitrary consistency checks on the given, newly created transaction before * it is passed back to application code for processing. * * <p> * If the implementation of this method detects any conflicts, it should throw an appropriate subclass of * {@link ChronoDBTransactionException}. * * @param tx * The transaction to verify. Must not be <code>null</code>. */ protected abstract void verifyTransaction(ChronoDBTransaction tx); // ===================================================================================================================== // INNER CLASSES // ===================================================================================================================== private class ExclusiveAutoLock extends AbstractAutoLock { private final AutoLock dbLockHolder; private ExclusiveAutoLock() { super(); // acquire the db lock holder... this.dbLockHolder = TemporalKeyValueStoreBase.this.getOwningDB().lockExclusive(); // ... but don't keep the lock for now (until 'doLock' is called) this.dbLockHolder.releaseLock(); } @Override protected void doLock() { this.dbLockHolder.acquireLock(); TemporalKeyValueStoreBase.this.branchLock.writeLock().lock(); } @Override protected void doUnlock() { TemporalKeyValueStoreBase.this.branchLock.writeLock().unlock(); this.dbLockHolder.releaseLock(); } } private class BranchExclusiveAutoLock extends AbstractAutoLock { private final AutoLock dbLockHolder; private BranchExclusiveAutoLock() { super(); // TODO c-39: We need to acquire the exclusive DB lock here to avoid deadlocks... // acquire the db lock holder... this.dbLockHolder = TemporalKeyValueStoreBase.this.getOwningDB().lockExclusive(); // ... but don't keep the lock for now (until 'doLock' is called) this.dbLockHolder.releaseLock(); } @Override protected void doLock() { this.dbLockHolder.acquireLock(); TemporalKeyValueStoreBase.this.branchLock.writeLock().lock(); } @Override protected void doUnlock() { TemporalKeyValueStoreBase.this.branchLock.writeLock().unlock(); this.dbLockHolder.releaseLock(); } } private class NonExclusiveAutoLock extends AbstractAutoLock { private final AutoLock dbLockHolder; private NonExclusiveAutoLock() { super(); // acquire the db lock holder... this.dbLockHolder = TemporalKeyValueStoreBase.this.getOwningDB().lockNonExclusive(); // ... but don't keep the lock for now (until 'doLock' is called) this.dbLockHolder.releaseLock(); } @Override protected void doLock() { this.dbLockHolder.acquireLock(); TemporalKeyValueStoreBase.this.branchLock.readLock().lock(); } @Override protected void doUnlock() { TemporalKeyValueStoreBase.this.branchLock.readLock().unlock(); this.dbLockHolder.releaseLock(); } } }
8,871
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AbstractBackupManager.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/engines/base/AbstractBackupManager.java
package org.chronos.chronodb.internal.impl.engines.base; import com.google.common.io.Files; import org.chronos.chronodb.api.BackupManager; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.DumpOption; import org.chronos.chronodb.api.dump.ChronoDBDumpFormat; import org.chronos.chronodb.api.dump.IncrementalBackupInfo; import org.chronos.chronodb.api.dump.IncrementalBackupResult; import org.chronos.chronodb.api.exceptions.ChronoDBStorageBackendException; import org.chronos.chronodb.internal.api.ChronoDBInternal; import org.chronos.chronodb.internal.api.stream.ObjectInput; import org.chronos.chronodb.internal.api.stream.ObjectOutput; import org.chronos.chronodb.internal.impl.dump.ChronoDBDumpUtil; import org.chronos.chronodb.internal.impl.dump.DumpOptions; import org.chronos.common.autolock.AutoLock; import java.io.File; import java.io.IOException; import static com.google.common.base.Preconditions.*; public abstract class AbstractBackupManager implements BackupManager { // ================================================================================================================= // FIELDS // ================================================================================================================= private final ChronoDBInternal owningDB; // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= public AbstractBackupManager(ChronoDBInternal db){ checkNotNull(db, "Precondition violation - argument 'db' must not be NULL!"); this.owningDB = db; } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public void writeDump(final File dumpFile, final DumpOption... dumpOptions) { checkNotNull(dumpFile, "Precondition violation - argument 'dumpFile' must not be NULL!"); if (dumpFile.exists()) { checkArgument(dumpFile.isFile(), "Precondition violation - argument 'dumpFile' must be a file (not a directory)!"); } else { try { File dumpParentDir = dumpFile.getParentFile(); if (!dumpParentDir.exists()) { boolean dirsCreated = dumpFile.getParentFile().mkdirs(); if (!dirsCreated) { throw new IOException("Failed to create directory path '" + dumpParentDir.getAbsolutePath() + "'! Please check access permissions."); } } boolean createdDumpFile = dumpFile.createNewFile(); if (!createdDumpFile) { throw new IOException("Failed to create file '" + dumpFile.getAbsolutePath() + "'! Please check access permissions."); } } catch (IOException e) { throw new ChronoDBStorageBackendException( "Failed to create dump file in '" + dumpFile.getAbsolutePath() + "'!", e); } } DumpOptions options = new DumpOptions(dumpOptions); try (AutoLock lock = this.owningDB.lockNonExclusive()) { try (ObjectOutput output = ChronoDBDumpFormat.createOutput(dumpFile, options)) { ChronoDBDumpUtil.dumpDBContentsToOutput(this.owningDB, output, options); } } } @Override public void readDump(final File dumpFile, final DumpOption... dumpOptions) { checkNotNull(dumpFile, "Precondition violation - argument 'dumpFile' must not be NULL!"); checkArgument(dumpFile.exists(), "Precondition violation - argument 'dumpFile' does not exist! Location: " + dumpFile.getAbsolutePath()); checkArgument(dumpFile.isFile(), "Precondition violation - argument 'dumpFile' must be a File (is a Directory)!"); this.owningDB.getConfiguration().assertNotReadOnly(); DumpOptions options = new DumpOptions(dumpOptions); try (AutoLock lock = this.owningDB.lockExclusive()) { try (ObjectInput input = ChronoDBDumpFormat.createInput(dumpFile, options)) { ChronoDBDumpUtil.readDumpContentsFromInput(this.owningDB, input, options); } } } // ================================================================================================================= // INTERNAL API // ================================================================================================================= protected ChronoDBInternal getOwningDb(){ return this.owningDB; } }
4,902
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AbstractTemporalDataMatrix.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/engines/base/AbstractTemporalDataMatrix.java
package org.chronos.chronodb.internal.impl.engines.base; import static com.google.common.base.Preconditions.*; import java.util.Collection; import java.util.Iterator; import java.util.Set; import org.chronos.chronodb.api.Order; import org.chronos.chronodb.api.key.TemporalKey; import org.chronos.chronodb.internal.api.TemporalDataMatrix; import org.chronos.chronodb.internal.util.IteratorUtils; import com.google.common.collect.Iterators; import com.google.common.collect.Sets; public abstract class AbstractTemporalDataMatrix implements TemporalDataMatrix { private final String keyspace; private long creationTimestamp; protected AbstractTemporalDataMatrix(final String keyspace, final long creationTimestamp) { checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkArgument(creationTimestamp >= 0, "Precondition violation - argument 'creationTimestamp' must not be negative!"); this.keyspace = keyspace; this.creationTimestamp = creationTimestamp; } @Override public String getKeyspace() { return this.keyspace; } @Override public long getCreationTimestamp() { return this.creationTimestamp; } protected void setCreationTimestamp(long creationTimestamp){ this.creationTimestamp = creationTimestamp; } @Override public Iterator<Long> getCommitTimestampsBetween(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'!"); Iterator<TemporalKey> iterator = this.getModificationsBetween(timestampLowerBound, timestampUpperBound); Iterator<Long> timestamps = Iterators.transform(iterator, TemporalKey::getTimestamp); return IteratorUtils.unique(timestamps); } @Override public Iterator<String> getChangedKeysAtCommit(final long commitTimestamp) { checkArgument(commitTimestamp >= 0, "Precondition violation - argument 'commitTimestamp' must not be negative!"); Iterator<TemporalKey> iterator = this.getModificationsBetween(commitTimestamp, commitTimestamp); return Iterators.transform(iterator, TemporalKey::getKey); } @Override public Collection<Long> purgeKey(final String key) { Set<Long> timestamps = Sets.newHashSet(this.history(key, 0, System.currentTimeMillis() + 1, Order.DESCENDING)); timestamps.forEach(timestamp -> this.purgeEntry(key, timestamp)); return timestamps; } }
2,735
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AbstractChronoDB.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/engines/base/AbstractChronoDB.java
package org.chronos.chronodb.internal.impl.engines.base; import com.google.common.collect.HashMultimap; import com.google.common.collect.Iterators; import com.google.common.collect.SetMultimap; import com.google.common.collect.Sets; import org.chronos.chronodb.api.Branch; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.CommitMetadataFilter; import org.chronos.chronodb.api.builder.transaction.ChronoDBTransactionBuilder; import org.chronos.chronodb.api.exceptions.ChronosBuildVersionConflictException; import org.chronos.chronodb.api.exceptions.InvalidTransactionBranchException; import org.chronos.chronodb.api.exceptions.InvalidTransactionTimestampException; import org.chronos.chronodb.internal.api.*; import org.chronos.chronodb.internal.api.stream.ChronoDBEntry; import org.chronos.chronodb.internal.api.stream.CloseableIterator; import org.chronos.chronodb.internal.impl.DefaultTransactionConfiguration; import org.chronos.chronodb.internal.impl.builder.transaction.DefaultTransactionBuilder; import org.chronos.chronodb.internal.impl.dump.CommitMetadataMap; import org.chronos.chronodb.internal.util.ThreadBound; import org.chronos.common.autolock.AutoLock; import org.chronos.common.version.ChronosVersion; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import static com.google.common.base.Preconditions.*; public abstract class AbstractChronoDB implements ChronoDB, ChronoDBInternal { private static final Logger log = LoggerFactory.getLogger(AbstractChronoDB.class); protected final ReadWriteLock dbLock; private final ChronoDBConfiguration configuration; private final Set<ChronoDBShutdownHook> shutdownHooks; private final CommitMetadataFilter commitMetadataFilter; private CommitTimestampProvider commitTimestampProvider; private final ThreadBound<AutoLock> exclusiveLockHolder; private final ThreadBound<AutoLock> nonExclusiveLockHolder; private boolean closed = false; protected AbstractChronoDB(final ChronoDBConfiguration configuration) { checkNotNull(configuration, "Precondition violation - argument 'configuration' must not be NULL!"); this.configuration = configuration; this.dbLock = new ReentrantReadWriteLock(false); this.exclusiveLockHolder = ThreadBound.createWeakReference(); this.nonExclusiveLockHolder = ThreadBound.createWeakReference(); this.shutdownHooks = Collections.synchronizedSet(Sets.newHashSet()); this.commitMetadataFilter = this.createMetadataFilterFromConfiguration(configuration); } // ================================================================================================================= // POST CONSTRUCT // ================================================================================================================= @Override public void postConstruct() { // check if any branch needs recovery (we do this even in read-only mode, as the DB // might not be readable otherwise) for (Branch branch : this.getBranchManager().getBranches()) { TemporalKeyValueStore tkvs = ((BranchInternal) branch).getTemporalKeyValueStore(); tkvs.performStartupRecoveryIfRequired(); } this.commitTimestampProvider = new CommitTimestampProviderImpl(this.getBranchManager().getMaxNowAcrossAllBranches()); } // ================================================================================================================= // SHUTDOWN HANDLING // ================================================================================================================= public void addShutdownHook(final ChronoDBShutdownHook hook) { checkNotNull(hook, "Precondition violation - argument 'hook' must not be NULL!"); try (AutoLock lock = this.lockNonExclusive()) { this.shutdownHooks.add(hook); } } public void removeShutdownHook(final ChronoDBShutdownHook hook) { checkNotNull(hook, "Precondition violation - argument 'hook' must not be NULL!"); try (AutoLock lock = this.lockNonExclusive()) { this.shutdownHooks.remove(hook); } } @Override public final void close() { if (this.isClosed()) { return; } try (AutoLock lock = this.lockExclusive()) { for (ChronoDBShutdownHook hook : this.shutdownHooks) { hook.onShutdown(); } this.closed = true; } } @Override public final boolean isClosed() { return this.closed; } // ================================================================================================================= // TRANSACTION HANDLING // ================================================================================================================= @Override public ChronoDBTransactionBuilder txBuilder() { return new DefaultTransactionBuilder(this); } @Override public ChronoDBTransaction tx(final TransactionConfigurationInternal configuration) { checkNotNull(configuration, "Precondition violation - argument 'configuration' must not be NULL!"); if (this.getDatebackManager().isDatebackRunning() && !configuration.isAllowedDuringDateback()) { throw new IllegalStateException( "Unable to open transaction: this database is currently executing a Dateback process!"); } try (AutoLock lock = this.lockNonExclusive()) { String branchName = configuration.getBranch(); if (this.getBranchManager().existsBranch(branchName) == false) { throw new InvalidTransactionBranchException( "There is no branch '" + branchName + "' in this ChronoDB!"); } TemporalKeyValueStore tkvs = this.getTKVS(branchName); long now = tkvs.getNow(); if (configuration.isTimestampNow() == false && configuration.getTimestamp() > now) { if (log.isDebugEnabled()) { log.debug("Invalid timestamp. Requested = " + configuration.getTimestamp() + ", now = " + now + ", branch = '" + branchName + "'"); } throw new InvalidTransactionTimestampException( "Cannot open transaction at the given date or timestamp: it's after the latest commit! Latest commit: " + now + ", transaction timestamp: " + configuration.getTimestamp() + ", branch: " + branchName); } TransactionConfigurationInternal txConfig = configuration; if (this.getConfiguration().isReadOnly()) { // set the read-only flag on every transaction txConfig = new DefaultTransactionConfiguration(configuration, c -> c.setReadOnly(true)); } return tkvs.tx(txConfig); } } // ================================================================================================================= // DUMP CREATION & DUMP LOADING // ================================================================================================================= @Override public CloseableIterator<ChronoDBEntry> entryStream() { return this.entryStream(0L, System.currentTimeMillis()); } @Override public CloseableIterator<ChronoDBEntry> entryStream(long minTimestamp, long maxTimestamp) { Set<String> branchNames = this.getBranchManager().getBranchNames(); Iterator<String> branchIterator = branchNames.iterator(); Iterator<CloseableIterator<ChronoDBEntry>> branchStreams = Iterators.transform(branchIterator, (final String branch) -> entryStream(branch, minTimestamp, maxTimestamp) ); return CloseableIterator.concat(branchStreams); } @Override public CloseableIterator<ChronoDBEntry> entryStream(String branch, long minTimestamp, long maxTimestamp) { checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); if (!this.getBranchManager().existsBranch(branch)) { throw new IllegalArgumentException("There is no branch named '" + branch + "'!"); } checkArgument(minTimestamp >= 0, "Precondition violation - argument 'minTimestamp' must not be negative!"); checkArgument(maxTimestamp >= 0, "Precondition violation - argument 'maxTimestamp' must not be negative!"); checkArgument(minTimestamp <= maxTimestamp, "Precondition violation - argument 'minTimestamp' must be less than or equal to 'maxTimestamp'!"); return this.getTKVS(branch).allEntriesIterator(minTimestamp, maxTimestamp); } @Override public void loadEntries(final List<ChronoDBEntry> entries) { checkNotNull(entries, "Precondition violation - argument 'entries' must not be NULL!"); this.loadEntries(entries, false); } protected void loadEntries(final List<ChronoDBEntry> entries, final boolean force) { SetMultimap<String, ChronoDBEntry> branchToEntries = HashMultimap.create(); for (ChronoDBEntry entry : entries) { String branchName = entry.getIdentifier().getBranchName(); branchToEntries.put(branchName, entry); } // insert into the branches for (String branchName : branchToEntries.keySet()) { Set<ChronoDBEntry> branchEntries = branchToEntries.get(branchName); BranchInternal branch = this.getBranchManager().getBranch(branchName); branch.getTemporalKeyValueStore().insertEntries(branchEntries, force); } } @Override public void loadCommitTimestamps(final CommitMetadataMap commitMetadata) { checkNotNull(commitMetadata, "Precondition violation - argument 'commitMetadata' must not be NULL!"); for (String branchName : commitMetadata.getContainedBranches()) { SortedMap<Long, Object> branchCommitMetadata = commitMetadata.getCommitMetadataForBranch(branchName); BranchInternal branch = this.getBranchManager().getBranch(branchName); CommitMetadataStore metadataStore = branch.getTemporalKeyValueStore().getCommitMetadataStore(); for (Entry<Long, Object> entry : branchCommitMetadata.entrySet()) { metadataStore.put(entry.getKey(), entry.getValue()); } } } // ================================================================================================================= // LOCKING // ================================================================================================================= @Override public AutoLock lockExclusive() { AutoLock lockHolder = this.exclusiveLockHolder.get(); if (lockHolder == null) { lockHolder = AutoLock.createBasicLockHolderFor(this.dbLock.writeLock()); this.exclusiveLockHolder.set(lockHolder); } // lockHolder.releaseLock() is called on lockHolder.close() lockHolder.acquireLock(); return lockHolder; } @Override public AutoLock lockNonExclusive() { AutoLock lockHolder = this.nonExclusiveLockHolder.get(); if (lockHolder == null) { lockHolder = AutoLock.createBasicLockHolderFor(this.dbLock.readLock()); this.nonExclusiveLockHolder.set(lockHolder); } // lockHolder.releaseLock() is called on lockHolder.close() lockHolder.acquireLock(); return lockHolder; } // ================================================================================================================= // MISCELLANEOUS // ================================================================================================================= @Override public ChronoDBConfiguration getConfiguration() { return this.configuration; } protected TemporalKeyValueStore getTKVS(final String branchName) { BranchInternal branch = this.getBranchManager().getBranch(branchName); return branch.getTemporalKeyValueStore(); } @Override public CommitMetadataFilter getCommitMetadataFilter() { return this.commitMetadataFilter; } protected CommitMetadataFilter createMetadataFilterFromConfiguration(final ChronoDBConfiguration configuration) { Class<? extends CommitMetadataFilter> filterClass = configuration.getCommitMetadataFilterClass(); if (filterClass == null) { // no filter specified return null; } try { Constructor<? extends CommitMetadataFilter> constructor = filterClass.getConstructor(); if (!constructor.isAccessible()) { constructor.setAccessible(true); } return constructor.newInstance(); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) { log.warn("Configuration warning: The given Commit Metadata Filter class '" + filterClass.getName() + "' could not be instantiated (" + e.getClass().getSimpleName() + ")! Does it have a default constructor? No filter will be used."); return null; } } @Override public ChronosVersion getCurrentChronosVersion() { return ChronosVersion.getCurrentVersion(); } @Override public CommitTimestampProvider getCommitTimestampProvider() { return commitTimestampProvider; } // ===================================================================================================================== // ABSTRACT METHOD DECLARATIONS // ===================================================================================================================== /** * Updates the Chronos Build Version in the database. * * <p> * Implementations of this method should follow this algorithm: * <ol> * <li>Check if the version identifier in the database exists. * <ol> * <li>If there is no version identifier, write {@link ChronosVersion#getCurrentVersion()}. * <li>If there is a version identifier, and it is smaller than {@link ChronosVersion#getCurrentVersion()}, * overwrite it (<i>Note:</i> in the future, we may perform data migration steps here). * <li>If there is a version identifier larger than {@link ChronosVersion#getCurrentVersion()}, throw a * {@link ChronosBuildVersionConflictException}. * </ol> * </ol> * * @param readOnly Set to <code>true</code> if the DB is in read-only mode. If read-only mode is enabled, * no changes must be performed to the persistent data. If the current software version is * incompatible with the persistent format in any way (e.g. a migration would be necessary), * an exception should be thrown if read-only is enabled. * * @return The current version of chronos which was originally stored in the database */ protected abstract ChronosVersion updateBuildVersionInDatabase(boolean readOnly); // ================================================================================================================= // INNER CLASSES // ================================================================================================================= public interface ChronoDBShutdownHook { public void onShutdown(); } }
15,838
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ThreadSafeChronoDBTransaction.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/engines/base/ThreadSafeChronoDBTransaction.java
package org.chronos.chronodb.internal.impl.engines.base; import org.chronos.chronodb.api.ChangeSetEntry; import org.chronos.chronodb.api.PutOption; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.internal.api.TemporalKeyValueStore; public class ThreadSafeChronoDBTransaction extends StandardChronoDBTransaction { public ThreadSafeChronoDBTransaction(final TemporalKeyValueStore tkvs, final long timestamp, final String branchIdentifier, final Configuration configuration) { super(tkvs, timestamp, branchIdentifier, configuration); } @Override protected synchronized void putInternal(final QualifiedKey key, final Object value, final PutOption[] options) { ChangeSetEntry entry = ChangeSetEntry.createChange(key, value, options); this.changeSet.put(key, entry); } @Override protected synchronized void removeInternal(final QualifiedKey key) { ChangeSetEntry entry = ChangeSetEntry.createDeletion(key); this.changeSet.put(key, entry); } }
1,086
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AbstractTemporalKeyValueStore.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/engines/base/AbstractTemporalKeyValueStore.java
package org.chronos.chronodb.internal.impl.engines.base; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Objects; import com.google.common.collect.HashMultimap; import com.google.common.collect.Iterators; import com.google.common.collect.ListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimaps; import com.google.common.collect.SetMultimap; import com.google.common.collect.Sets; import org.apache.commons.lang3.tuple.Pair; import org.chronos.chronodb.api.Branch; import org.chronos.chronodb.api.BranchHeadStatistics; import org.chronos.chronodb.api.ChangeSetEntry; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.CommitMetadataFilter; import org.chronos.chronodb.api.Dateback; import org.chronos.chronodb.api.Dateback.KeyspaceValueTransformation; import org.chronos.chronodb.api.DuplicateVersionEliminationMode; import org.chronos.chronodb.api.Order; import org.chronos.chronodb.api.PutOption; import org.chronos.chronodb.api.SerializationManager; import org.chronos.chronodb.api.conflict.AtomicConflict; import org.chronos.chronodb.api.conflict.ConflictResolutionStrategy; import org.chronos.chronodb.api.exceptions.ChronoDBCommitException; import org.chronos.chronodb.api.exceptions.ChronoDBCommitMetadataRejectedException; import org.chronos.chronodb.api.exceptions.DatebackException; import org.chronos.chronodb.api.exceptions.InvalidTransactionBranchException; import org.chronos.chronodb.api.exceptions.InvalidTransactionTimestampException; import org.chronos.chronodb.api.key.ChronoIdentifier; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.api.key.TemporalKey; import org.chronos.chronodb.internal.api.BranchInternal; import org.chronos.chronodb.internal.api.ChronoDBInternal; import org.chronos.chronodb.internal.api.GetResult; import org.chronos.chronodb.internal.api.MutableTransactionConfiguration; import org.chronos.chronodb.internal.api.Period; import org.chronos.chronodb.internal.api.TemporalDataMatrix; import org.chronos.chronodb.internal.api.TemporalKeyValueStore; import org.chronos.chronodb.internal.api.cache.CacheGetResult; import org.chronos.chronodb.internal.api.cache.ChronoDBCache; import org.chronos.chronodb.internal.api.index.IndexManagerInternal; import org.chronos.chronodb.internal.api.stream.ChronoDBEntry; import org.chronos.chronodb.internal.api.stream.CloseableIterator; import org.chronos.chronodb.internal.impl.BranchHeadStatisticsImpl; import org.chronos.chronodb.internal.impl.DefaultTransactionConfiguration; import org.chronos.chronodb.internal.impl.conflict.AtomicConflictImpl; import org.chronos.chronodb.internal.impl.stream.AbstractCloseableIterator; 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.autolock.AutoLock; import org.chronos.common.exceptions.UnknownEnumLiteralException; import org.chronos.common.serialization.KryoManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.Set; import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.*; public abstract class AbstractTemporalKeyValueStore extends TemporalKeyValueStoreBase implements TemporalKeyValueStore { private static final Logger log = LoggerFactory.getLogger(AbstractTemporalKeyValueStore.class); // ================================================================================================================= // FIELDS // ================================================================================================================= /** * The commit lock is a plain reentrant lock that protects a single branch from concurrent commits. * * <p> * Please note that this lock may be acquired if and only if the current thread is holding all of the following * locks: * <ul> * <li>Database lock (read or write) * <li>Branch lock (read or write) * </ul> * <p> * Also note that (as the name implies) this lock is for commit operations only. Read operations do not need to * acquire this lock at all. */ private final Object commitLock = new Object(); private final BranchInternal owningBranch; private final ChronoDBInternal owningDB; protected final Map<String, TemporalDataMatrix> keyspaceToMatrix = Maps.newHashMap(); /** * This lock is used to protect incremental commit data from illegal concurrent access. */ protected final Object incrementalCommitLock = new Object(); /** * This field is used to keep track of the transaction that is currently executing an incremental commit. */ protected ChronoDBTransaction incrementalCommitTransaction = null; /** * This timestamp will be written to during incremental commits, all of them will write to this timestamp. */ protected long incrementalCommitTimestamp = -1L; protected Consumer<ChronoDBTransaction> debugCallbackBeforePrimaryIndexUpdate; protected Consumer<ChronoDBTransaction> debugCallbackBeforeSecondaryIndexUpdate; protected Consumer<ChronoDBTransaction> debugCallbackBeforeMetadataUpdate; protected Consumer<ChronoDBTransaction> debugCallbackBeforeCacheUpdate; protected Consumer<ChronoDBTransaction> debugCallbackBeforeNowTimestampUpdate; protected Consumer<ChronoDBTransaction> debugCallbackBeforeTransactionCommitted; // ===================================================================================================================== // CONSTRUCTOR // ===================================================================================================================== protected AbstractTemporalKeyValueStore(final ChronoDBInternal owningDB, final BranchInternal owningBranch) { checkNotNull(owningBranch, "Precondition violation - argument 'owningBranch' must not be NULL!"); checkNotNull(owningDB, "Precondition violation - argument 'owningDB' must not be NULL!"); this.owningDB = owningDB; this.owningBranch = owningBranch; this.owningBranch.setTemporalKeyValueStore(this); } // ================================================================================================================= // PUBLIC API (common implementations) // ================================================================================================================= @Override public void performStartupRecoveryIfRequired() { WriteAheadLogToken walToken = this.getWriteAheadLogTokenIfExists(); if (walToken == null) { // we have no Write-Ahead-Log token. This means that there was no ongoing commit // during the shutdown of the database. Therefore, no recovery is required. return; } log.warn("There has been an error during the last shutdown. ChronoDB will attempt to recover to the last consistent state (this may take a few minutes)."); // we have a WAL-Token, so we need to perform a recovery. We roll back to the // last valid timestamp before the commit (which was interrupted by JVM shutdown) has occurred. long timestamp = walToken.getNowTimestampBeforeCommit(); // we must assume that all keyspaces were modified (in the worst case) Set<String> modifiedKeyspaces = this.getAllKeyspaces(); // we must also assume that our index is broken (in the worst case) boolean touchedIndex = true; // perform the rollback this.performRollbackToTimestamp(timestamp, modifiedKeyspaces, touchedIndex); this.clearWriteAheadLogToken(); } @Override public Branch getOwningBranch() { return this.owningBranch; } @Override public ChronoDBInternal getOwningDB() { return this.owningDB; } public Set<String> getAllKeyspaces() { try (AutoLock lock = this.lockNonExclusive()) { // produce a duplicate of the set, because the actual key set changes over time and may lead to // unexpected "ConcurrentModificationExceptions" in the calling code when used for iteration purposes. Set<String> keyspaces = Sets.newHashSet(this.keyspaceToMatrix.keySet()); // add the keyspaces of the origin recursively (if there is an origin) if (this.isMasterBranchTKVS() == false) { ChronoDBTransaction parentTx = this.getOriginBranchTKVS() .tx(this.getOwningBranch().getBranchingTimestamp()); keyspaces.addAll(this.getOriginBranchTKVS().getKeyspaces(parentTx)); } return Collections.unmodifiableSet(keyspaces); } } @Override public Set<String> getKeyspaces(final ChronoDBTransaction tx) { checkNotNull(tx, "Precondition violation - argument 'tx' must not be NULL!"); return this.getKeyspaces(tx.getTimestamp()); } @Override public Set<String> getKeyspaces(final long timestamp) { checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); try (AutoLock lock = this.lockNonExclusive()) { // produce a duplicate of the set, because the actual key set changes over time and may lead to // unexpected "ConcurrentModificationExceptions" in the calling code when used for iteration purposes. Set<String> keyspaces = Sets.newHashSet(); for (Entry<String, TemporalDataMatrix> entry : this.keyspaceToMatrix.entrySet()) { String keyspaceName = entry.getKey(); TemporalDataMatrix matrix = entry.getValue(); if (matrix.getCreationTimestamp() <= timestamp) { keyspaces.add(keyspaceName); } } // add the keyspaces of the origin recursively (if there is an origin) if (this.isMasterBranchTKVS() == false) { long branchingTimestamp = this.getOwningBranch().getBranchingTimestamp(); keyspaces.addAll(this.getOriginBranchTKVS().getKeyspaces(branchingTimestamp)); } return Collections.unmodifiableSet(keyspaces); } } @Override public long getNow() { try (AutoLock lock = this.lockNonExclusive()) { long nowInternal = this.getNowInternal(); long now = Math.max(this.getOwningBranch().getBranchingTimestamp(), nowInternal); // see if we have an open transaction WriteAheadLogToken walToken = this.getWriteAheadLogTokenIfExists(); if (walToken != null) { // transaction is open, we must not read after the transaction start now = Math.min(now, walToken.getNowTimestampBeforeCommit()); } return now; } } @Override public long performCommit(final ChronoDBTransaction tx, final Object commitMetadata) { checkNotNull(tx, "Precondition violation - argument 'tx' must not be NULL!"); this.assertThatTransactionMayPerformCommit(tx); boolean performanceLoggingActive = this.owningDB.getConfiguration().isCommitPerformanceLoggingActive(); // Note: the locking process here is special. We acquire the following locks (in this order): // // 1) DB Read Lock // Reason: Writing on one branch does not need to block the others. The case that simultaneous writes // occur on the same branch is handled by different locks. The DB Write Lock is only intended for very // drastic operations, such as branch removal or DB dump reading. // // 2) Branch Read Lock // Reason: We only acquire the read lock on the branch. This is because we want read transactions to be // able to continue reading, even though we are writing (on a different version). The branch write lock // is intended only for drastic operations that prevent reading, such as reindexing. // // 3) Commit Lock // Reason: This is not a read-write lock, this is a plain old lock. It prevents concurrent writes on the // same branch. Read operations never acquire this lock. String perfLogPrefix = "[PERF ChronoDB] Commit (" + tx.getBranchName() + "@" + tx.getTimestamp() + ")"; long timeBeforeLockAcquisition = System.currentTimeMillis(); try (AutoLock lock = this.lockBranchExclusive()) { synchronized (this.commitLock) { try { if (performanceLoggingActive) { log.info(perfLogPrefix + " -> Lock Acquisition: " + (System.currentTimeMillis() - timeBeforeLockAcquisition) + "ms."); } if (this.isIncrementalCommitProcessOngoing() && tx.getChangeSet().isEmpty() == false) { // "terminate" the incremental commit process with a FINAL incremental commit, // then continue with a true commit that has an EMPTY change set tx.commitIncremental(); } if (this.isIncrementalCommitProcessOngoing() == false) { if (tx.getChangeSet().isEmpty()) { // change set is empty -> there is nothing to commit return -1; } } long time = 0; if (this.isIncrementalCommitProcessOngoing()) { // use the incremental commit timestamp time = this.incrementalCommitTimestamp; } else { // use the current transaction time time = this.waitForNextValidCommitTimestamp(); } long beforeCommitMetadataFilter = System.currentTimeMillis(); CommitMetadataFilter filter = this.getOwningDB().getCommitMetadataFilter(); if (filter != null) { if (filter.doesAccept(tx.getBranchName(), time, commitMetadata) == false) { String className = (commitMetadata == null ? "NULL" : commitMetadata.getClass().getName()); throw new ChronoDBCommitMetadataRejectedException("The given Commit Metadata object (class: " + className + ") was rejected by the commit metadata filter! Cancelling commit."); } } if (performanceLoggingActive) { log.info(perfLogPrefix + " -> Commit Metadata Filter: " + (System.currentTimeMillis() - beforeCommitMetadataFilter) + "ms."); } long beforeChangeSetAnalysis = System.currentTimeMillis(); ChangeSet changeSet = this.analyzeChangeSet(tx, tx, time); if (performanceLoggingActive) { log.info(perfLogPrefix + " -> Change Set Analysis: " + (System.currentTimeMillis() - beforeChangeSetAnalysis) + "ms."); } if (this.isIncrementalCommitProcessOngoing() == false) { long beforeWalTokenHandling = System.currentTimeMillis(); // check that no WAL token exists on disk this.performRollbackToWALTokenIfExists(); // before we begin the writing to disk, we store a token as a file. This token // will allow us to recover on the next startup in the event that the JVM crashes or // is being shut down during the commit process. WriteAheadLogToken token = new WriteAheadLogToken(this.getNow(), time); this.performWriteAheadLog(token); if (performanceLoggingActive) { log.info(perfLogPrefix + " -> WAL Token Handling: " + (System.currentTimeMillis() - beforeWalTokenHandling) + "ms."); } } // remember if we started to work with the index boolean touchedIndex = false; if (this.isIncrementalCommitProcessOngoing()) { // when committing incrementally, always assume that we touched the index, because // some of the preceeding incremental commits has very likely touched it. touchedIndex = true; } try { // here, we perform the actual *write* work. this.debugCallbackBeforePrimaryIndexUpdate(tx); long beforePrimaryIndexUpdate = System.currentTimeMillis(); this.updatePrimaryIndex(perfLogPrefix + " -> Primary Index Update", time, changeSet); if (performanceLoggingActive) { log.info(perfLogPrefix + " -> Primary Index Update: " + (System.currentTimeMillis() - beforePrimaryIndexUpdate) + "ms."); } this.debugCallbackBeforeSecondaryIndexUpdate(tx); long beforeSecondaryIndexupdate = System.currentTimeMillis(); touchedIndex = this.updateSecondaryIndices(changeSet) || touchedIndex; if (performanceLoggingActive) { log.info(perfLogPrefix + " -> Secondary Index Update: " + (System.currentTimeMillis() - beforeSecondaryIndexupdate) + "ms."); } this.debugCallbackBeforeMetadataUpdate(tx); // write the commit metadata object (this will also register the commit, even if no metadata is // given) long beforeCommitMetadataStoring = System.currentTimeMillis(); this.getCommitMetadataStore().put(time, commitMetadata); if (performanceLoggingActive) { log.info(perfLogPrefix + " -> Commit Metadata Store: " + (System.currentTimeMillis() - beforeCommitMetadataStoring) + "ms."); } this.debugCallbackBeforeCacheUpdate(tx); // update the cache (if any) long beforeCacheUpdate = System.currentTimeMillis(); if (this.getCache() != null && this.isIncrementalCommitProcessOngoing()) { this.getCache().rollbackToTimestamp(this.getNow()); } this.writeCommitThroughCache(tx.getBranchName(), time, changeSet.getEntriesByKeyspace()); if (performanceLoggingActive) { log.info(perfLogPrefix + " -> Cache Update: " + (System.currentTimeMillis() - beforeCacheUpdate) + "ms."); } this.debugCallbackBeforeNowTimestampUpdate(tx); long beforeSetNow = System.currentTimeMillis(); this.setNow(time); if (performanceLoggingActive) { log.info(perfLogPrefix + " -> Set Now: " + (System.currentTimeMillis() - beforeSetNow) + "ms."); } this.debugCallbackBeforeTransactionCommitted(tx); } catch (Throwable t) { // an error occurred, we need to perform the rollback this.rollbackCurrentCommit(changeSet, touchedIndex); // throw the commit exception throw new ChronoDBCommitException( "An error occurred during the commit. Please see root cause for details.", t); } long beforeClearWalToken = System.currentTimeMillis(); // everything ok in this commit, we can clear the write ahead log this.clearWriteAheadLogToken(); if (performanceLoggingActive) { log.info(perfLogPrefix + " -> Clear WAL token: " + (System.currentTimeMillis() - beforeClearWalToken) + "ms."); } // clear the branch head statistics cache, forcing a recalculation on the next access this.owningDB.getStatisticsManager().clearBranchHeadStatistics(tx.getBranchName()); return time; } finally { if (this.isIncrementalCommitProcessOngoing()) { this.terminateIncrementalCommitProcess(); } long beforeDestroyKryo = System.currentTimeMillis(); // drop the kryo instance we have been using, as it has some internal caches that just consume memory KryoManager.destroyKryo(); if (performanceLoggingActive) { log.info(perfLogPrefix + " -> Destroy Kryo: " + (System.currentTimeMillis() - beforeDestroyKryo) + "ms."); } } } } } @Override public long performCommitIncremental(final ChronoDBTransaction tx) throws ChronoDBCommitException { checkNotNull(tx, "Precondition violation - argument 'tx' must not be NULL!"); String perfLogPrefix = "[PERF ChronoDB] Commit (" + tx.getBranchName() + "@" + tx.getTimestamp() + ")"; try (AutoLock lock = this.lockBranchExclusive()) { // make sure that this transaction may start (or continue with) an incremental commit process this.assertThatTransactionMayPerformIncrementalCommit(tx); // set up the incremental commit process, if this is the first incremental commit if (this.isFirstIncrementalCommit(tx)) { this.setUpIncrementalCommit(tx); this.performRollbackToWALTokenIfExists(); // store the WAL token. We will need it to recover if the JVM crashes or shuts down during the process WriteAheadLogToken token = new WriteAheadLogToken(this.getNow(), this.incrementalCommitTimestamp); this.performWriteAheadLog(token); } synchronized (this.commitLock) { try { long time = this.incrementalCommitTimestamp; if (tx.getChangeSet().isEmpty()) { // change set is empty -> there is nothing to commit return this.incrementalCommitTimestamp; } // prepare a transaction to fetch the "old values" with. The old values // are the ones that existed BEFORE we started the incremental commit process. ChronoDBTransaction oldValueTx = this.tx(tx.getBranchName(), this.getNow()); ChangeSet changeSet = this.analyzeChangeSet(tx, oldValueTx, time); try { // here, we perform the actual *write* work. this.debugCallbackBeforePrimaryIndexUpdate(tx); this.updatePrimaryIndex(perfLogPrefix + " -> Primary Index Update", time, changeSet); this.debugCallbackBeforeSecondaryIndexUpdate(tx); this.updateSecondaryIndices(changeSet); this.debugCallbackBeforeCacheUpdate(tx); // update the cache (if any) this.getCache().rollbackToTimestamp(this.getNow()); this.writeCommitThroughCache(tx.getBranchName(), time, changeSet.getEntriesByKeyspace()); this.debugCallbackBeforeTransactionCommitted(tx); } catch (Throwable t) { // an error occurred, we need to perform the rollback this.performRollbackToTimestamp(this.getNow(), changeSet.getEntriesByKeyspace().keySet(), true); // as a safety measure, we also have to clear the cache this.getCache().clear(); // terminate the incremental commit process this.terminateIncrementalCommitProcess(); // after rolling back, we can clear the write ahead log this.clearWriteAheadLogToken(); // throw the commit exception throw new ChronoDBCommitException( "An error occurred during the commit. Please see root cause for details.", t); } // note: we do NOT clear the write-ahead log here, because we are still waiting for the terminating // full commit. } finally { // drop the kryo instance we have been using, as it has some internal caches that just consume memory KryoManager.destroyKryo(); } } return this.incrementalCommitTimestamp; } } private void performRollbackToWALTokenIfExists() { // check if a WAL token exists WriteAheadLogToken walToken = this.getWriteAheadLogTokenIfExists(); if (walToken != null) { // a write-ahead log token already exists in our store. This means that another transaction // failed mid-way. log.warn("The transaction log indicates that a transaction after timestamp '" + walToken.getNowTimestampBeforeCommit() + "' has failed. Will perform a rollback to timestamp '" + walToken.getNowTimestampBeforeCommit() + "'. This may take a while."); this.performRollbackToTimestamp(walToken.getNowTimestampBeforeCommit(), this.getAllKeyspaces(), true); } } @Override public void performIncrementalRollback(final ChronoDBTransaction tx) { checkNotNull(tx, "Precondition violation - argument 'tx' must not be NULL!"); if (this.isIncrementalCommitProcessOngoing() == false) { throw new IllegalStateException("There is no ongoing incremental commit process. Cannot perform rollback."); } if (this.incrementalCommitTransaction != tx) { throw new IllegalArgumentException( "Can only rollback an incremental commit on the same transaction that started the incremental commit process."); } this.performRollbackToTimestamp(this.getNow(), this.getAllKeyspaces(), true); // as a safety measure, we also have to clear the cache this.getCache().clear(); this.terminateIncrementalCommitProcess(); // after rolling back, we can clear the write ahead log this.clearWriteAheadLogToken(); } @Override public Object performGet(final ChronoDBTransaction tx, final QualifiedKey key) { return this.performGet(tx.getBranchName(), key, tx.getTimestamp(), false); } @Override public byte[] performGetBinary(final ChronoDBTransaction tx, final QualifiedKey key) { return (byte[]) this.performGet(tx.getBranchName(), key, tx.getTimestamp(), true); } private Object performGet(final String branchName, final QualifiedKey qKey, final long timestamp, boolean binary) { try (AutoLock lock = this.lockNonExclusive()) { // binary gets are excluded from caching if (!binary) { // first, try to find the result in our cache CacheGetResult<Object> cacheGetResult = this.getCache().get(branchName, timestamp, qKey); if (cacheGetResult.isHit()) { Object result = cacheGetResult.getValue(); if (result == null) { return null; } // cache hit, return the result immediately if (this.getOwningDB().getConfiguration().isAssumeCachedValuesAreImmutable()) { // return directly return cacheGetResult.getValue(); } else { // return a copy return KryoManager.deepCopy(result); } } } // need to contact the backing store. 'performRangedGet' automatically caches the result. GetResult<?> getResult = this.performRangedGetInternal(branchName, qKey, timestamp, binary); if (getResult.isHit() == false) { return null; } else { return getResult.getValue(); } } } @Override @SuppressWarnings({"unchecked", "rawtypes"}) public GetResult<Object> performRangedGet(final ChronoDBTransaction tx, final QualifiedKey key) { return (GetResult) this.performRangedGetInternal(tx.getBranchName(), key, tx.getTimestamp(), false); } @Override @SuppressWarnings({"unchecked", "rawtypes"}) public GetResult<byte[]> performRangedGetBinary(final ChronoDBTransaction tx, final QualifiedKey key) { return (GetResult) this.performRangedGetInternal(tx.getBranchName(), key, tx.getTimestamp(), true); } protected GetResult<?> performRangedGetInternal(final String branchName, final QualifiedKey qKey, final long timestamp, final boolean binary) { checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!"); checkNotNull(qKey, "Precondition violation - argument 'qKey' must not be NULL!"); checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); try (AutoLock lock = this.lockNonExclusive()) { TemporalDataMatrix matrix = this.getMatrix(qKey.getKeyspace()); if (matrix == null) { if (this.isMasterBranchTKVS()) { // matrix doesn't exist, so the get returns null by definition. // In case of the ranged get, we return a result with a null value, and an // unlimited range. return GetResult.createNoValueResult(qKey, Period.eternal()); } else { // matrix doesn't exist in the child branch, re-route the request to the parent ChronoDBTransaction tempTx = this.createOriginBranchTx(timestamp); if (binary) { return this.getOriginBranchTKVS().performRangedGetBinary(tempTx, qKey); } else { return this.getOriginBranchTKVS().performRangedGet(tempTx, qKey); } } } // execute the query on the backend GetResult<byte[]> rangedResult = matrix.get(timestamp, qKey.getKey()); if (rangedResult.isHit() == false && this.isMasterBranchTKVS() == false) { // we did not find anything in our branch; re-route the request and try to find it in the origin branch ChronoDBTransaction tempTx = this.createOriginBranchTx(timestamp); if (binary) { return this.getOriginBranchTKVS().performRangedGetBinary(tempTx, qKey); } else { return this.getOriginBranchTKVS().performRangedGet(tempTx, qKey); } } // we do have a hit in our branch, so let's process it if (binary) { // we want the raw binary result, no need for deserialization or caching return rangedResult; } byte[] serialForm = rangedResult.getValue(); Object deserializedValue = null; Period range = rangedResult.getPeriod(); if (serialForm == null || serialForm.length <= 0) { deserializedValue = null; } else { deserializedValue = this.getOwningDB().getSerializationManager().deserialize(serialForm); } GetResult<Object> result = GetResult.create(qKey, deserializedValue, range); // cache the result this.getCache().cache(branchName, result); // depending on the configuration, we may need to duplicate the result before returning it if (this.getOwningDB().getConfiguration().isAssumeCachedValuesAreImmutable()) { // we may directly return the cached instance, as we can assume it to be immutable return result; } else { // we have to return a duplicate of the cached element, as we cannot assume it to be immutable, // and the client may change the returned element. If we did not duplicate it, changes by the // client to the returned element would modify our cache state. Object duplicatedValue = KryoManager.deepCopy(deserializedValue); return GetResult.create(qKey, duplicatedValue, range); } } } @Override public Set<String> performKeySet(final ChronoDBTransaction tx, final String keyspaceName) { checkNotNull(tx, "Precondition violation - argument 'tx' must not be NULL!"); checkNotNull(keyspaceName, "Precondition violation - argument 'keyspaceName' must not be NULL!"); return this.performKeySet(tx.getBranchName(), tx.getTimestamp(), keyspaceName); } public Set<String> performKeySet(final String branch, final long timestamp, final String keyspaceName) { checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); checkNotNull(keyspaceName, "Precondition violation - argument 'keyspaceName' must not be NULL!"); try (AutoLock lock = this.lockNonExclusive()) { TemporalDataMatrix matrix = this.getMatrix(keyspaceName); if (this.getOwningBranch().getOrigin() == null) { // we are master, directly apply changes if (matrix == null) { // keyspace is not present, return the empty set return Sets.newHashSet(); } KeySetModifications modifications = matrix.keySetModifications(timestamp); return Sets.newHashSet(modifications.getAdditions()); } else { // we are a sub-branch, accumulate changes along the way Branch origin = this.getOwningBranch().getOrigin(); long branchingTimestamp = this.getOwningBranch().getBranchingTimestamp(); long parentTimestamp; if (timestamp < branchingTimestamp) { parentTimestamp = timestamp; } else { parentTimestamp = branchingTimestamp; } ChronoDBTransaction tmpTX = this.getOwningDB().tx(origin.getName(), parentTimestamp); Set<String> keySet = tmpTX.keySet(keyspaceName); if (matrix == null) { // the matrix does not exist in this branch, i.e. nothing was added to it yet, // therefore the accumulated changes from our origins are complete return keySet; } else { // add our branch-local modifications KeySetModifications modifications = matrix.keySetModifications(timestamp); modifications.apply(keySet); } return keySet; } } } @Override public Iterator<Long> performHistory(final ChronoDBTransaction tx, final QualifiedKey key, final long lowerBound, final long upperBound, final Order order) { checkNotNull(tx, "Precondition violation - argument 'tx' must not be NULL!"); 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(upperBound >= lowerBound, "Precondition violation - argument 'upperBound' must be greater than or equal to argument 'lowerBound'!"); checkArgument(lowerBound <= tx.getTimestamp(), "Precondition violation - argument 'lowerBound' must be less than or equal to the transaction timestamp!"); checkArgument(upperBound <= tx.getTimestamp(), "Precondition violation - argument 'upperBound' must be less than or equal to the transaction timestamp!"); checkNotNull(order, "Precondition violation - argument 'order' must not be NULL!"); try (AutoLock lock = this.lockNonExclusive()) { TemporalDataMatrix matrix = this.getMatrix(key.getKeyspace()); if (matrix == null) { if (this.isMasterBranchTKVS()) { // keyspace doesn't exist, history is empty by definition return Collections.emptyIterator(); } else { // re-route the request and ask the parent branch ChronoDBTransaction tempTx = this.createOriginBranchTx(tx.getTimestamp()); //clamp the request range long newUpperBound = Math.min(tempTx.getTimestamp(), upperBound); long newLowerBound = Math.min(lowerBound, newUpperBound); return this.getOriginBranchTKVS().performHistory(tempTx, key, newLowerBound, newUpperBound, order); } } // the matrix exists in our branch, ask it for the history Iterator<Long> iterator = matrix.history(key.getKey(), lowerBound, upperBound, order); if (this.isMasterBranchTKVS()) { // we're done here return iterator; } else { // check if the entire range is within the range of this branch if (this.owningBranch.getBranchingTimestamp() < lowerBound) { // no need to ask our parent branch, we're done return iterator; } // ask our parent branch ChronoDBTransaction tempTx = this.createOriginBranchTx(tx.getTimestamp()); //clamp the request range long newUpperBound = Math.min(tempTx.getTimestamp(), upperBound); long newLowerBound = Math.min(lowerBound, newUpperBound); Iterator<Long> parentBranchIterator = this.getOriginBranchTKVS().performHistory(tempTx, key, newLowerBound, newUpperBound, order); switch (order) { case ASCENDING: // if we have ASCENDING order, we need to use our parent iterator first, then our own iterator return Iterators.concat(parentBranchIterator, iterator); case DESCENDING: // if we have DESCENDING order, we need to use our iterator first, then the parent iterator return Iterators.concat(iterator, parentBranchIterator); default: throw new UnknownEnumLiteralException(order); } } } } @Override public long performGetLastModificationTimestamp(final ChronoDBTransaction tx, final QualifiedKey key) { checkNotNull(tx, "Precondition violation - argument 'tx' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); try (AutoLock lock = this.lockNonExclusive()) { TemporalDataMatrix matrix = this.getMatrix(key.getKeyspace()); long lastCommitTimestamp = -1; if (matrix != null) { lastCommitTimestamp = matrix.lastCommitTimestamp(key.getKey(), tx.getTimestamp()); } if (lastCommitTimestamp < 0) { // there was no commit in OUR branch, but maybe in the parent? if (this.isMasterBranchTKVS()) { // keyspace doesn't exist, history is empty by definition return -1; } else { // re-route the request and ask the parent branch long newTransactionTimestamp = Math.min(tx.getTimestamp(), this.owningBranch.getBranchingTimestamp()); ChronoDBTransaction tempTx = this.createOriginBranchTx(newTransactionTimestamp); return this.getOriginBranchTKVS().performGetLastModificationTimestamp(tempTx, key); } } return lastCommitTimestamp; } } @Override public Iterator<TemporalKey> performGetModificationsInKeyspaceBetween(final ChronoDBTransaction tx, final String keyspace, final long timestampLowerBound, final long timestampUpperBound) { checkNotNull(tx, "Precondition violation - argument 'tx' must not be NULL!"); checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkArgument(timestampLowerBound >= 0, "Precondition violation - argument 'timestampLowerBound' must not be negative!"); checkArgument(timestampUpperBound >= 0, "Precondition violation - argument 'timestampUpperBound' must not be negative!"); checkArgument(timestampLowerBound <= tx.getTimestamp(), "Precondition violation - argument 'timestampLowerBound' must not exceed the transaction timestamp!"); checkArgument(timestampUpperBound <= tx.getTimestamp(), "Precondition violation - argument 'timestampUpperBound' must not exceed the transaction timestamp!"); checkArgument(timestampLowerBound <= timestampUpperBound, "Precondition violation - argument 'timestampLowerBound' must be less than or equal to 'timestampUpperBound'!"); try (AutoLock lock = this.lockNonExclusive()) { TemporalDataMatrix matrix = this.getMatrix(keyspace); if (matrix == null) { if (this.isMasterBranchTKVS()) { // keyspace doesn't exist, history is empty by definition return Collections.emptyIterator(); } else { // re-route the request and ask the parent branch ChronoDBTransaction tempTx = this.createOriginBranchTx(tx.getTimestamp()); //clamp the request range long newUpperBound = Math.min(tempTx.getTimestamp(), timestampUpperBound); long newLowerBound = Math.min(timestampLowerBound, newUpperBound); return this.getOriginBranchTKVS().performGetModificationsInKeyspaceBetween(tempTx, keyspace, newLowerBound, newUpperBound); } } // the matrix exists in our branch, ask it for the history Iterator<TemporalKey> iterator = matrix.getModificationsBetween(timestampLowerBound, timestampUpperBound); if (this.isMasterBranchTKVS()) { // we're done here return iterator; } else { // check if the entire range is within the range of this branch if (this.owningBranch.getBranchingTimestamp() < timestampLowerBound) { // no need to ask our parent branch, we're done return iterator; } // ask our parent branch ChronoDBTransaction tempTx = this.createOriginBranchTx(tx.getTimestamp()); //clamp the request range long newUpperBound = Math.min(tempTx.getTimestamp(), timestampUpperBound); long newLowerBound = Math.min(timestampLowerBound, newUpperBound); Iterator<TemporalKey> parentBranchIterator = this.getOriginBranchTKVS().performGetModificationsInKeyspaceBetween(tempTx, keyspace, newLowerBound, newUpperBound); return Iterators.concat(iterator, parentBranchIterator); } } } @Override public Iterator<Long> performGetCommitTimestampsBetween(final ChronoDBTransaction tx, final long from, final long to, final Order order, final boolean includeSystemInternalCommits) { checkNotNull(tx, "Precondition violation - argument 'tx' must not be NULL!"); checkArgument(from >= 0, "Precondition violation - argument 'from' must not be negative!"); checkArgument(from <= tx.getTimestamp(), "Precondition violation - argument 'from' must not be larger than the transaction timestamp!"); checkArgument(to >= 0, "Precondition violation - argument 'to' must not be negative!"); checkArgument(to <= tx.getTimestamp(), "Precondition violation - argument 'to' must not be larger than the transaction timestamp!"); checkNotNull(order, "Precondition violation - argument 'order' must not be NULL!"); return this.getCommitMetadataStore().getCommitTimestampsBetween(from, to, order, includeSystemInternalCommits); } @Override public Iterator<Entry<Long, Object>> performGetCommitMetadataBetween(final ChronoDBTransaction tx, final long from, final long to, final Order order, final boolean includeSystemInternalCommits) { checkNotNull(tx, "Precondition violation - argument 'tx' must not be NULL!"); checkArgument(from >= 0, "Precondition violation - argument 'from' must not be negative!"); checkArgument(from <= tx.getTimestamp(), "Precondition violation - argument 'from' must not be larger than the transaction timestamp!"); checkArgument(to >= 0, "Precondition violation - argument 'to' must not be negative!"); checkArgument(to <= tx.getTimestamp(), "Precondition violation - argument 'to' must not be larger than the transaction timestamp!"); checkNotNull(order, "Precondition violation - argument 'order' must not be NULL!"); try (AutoLock lock = this.lockNonExclusive()) { return this.getCommitMetadataStore().getCommitMetadataBetween(from, to, order, includeSystemInternalCommits); } } @Override public Iterator<Long> performGetCommitTimestampsPaged(final ChronoDBTransaction tx, final long minTimestamp, final long maxTimestamp, final int pageSize, final int pageIndex, final Order order, final boolean includeSystemInternalCommits) { checkNotNull(tx, "Precondition violation - argument 'tx' must not be NULL!"); checkArgument(minTimestamp >= 0, "Precondition violation - argument 'minTimestamp' must not be negative!"); checkArgument(minTimestamp <= tx.getTimestamp(), "Precondition violation - argument 'minTimestamp' must not be larger than the transaction timestamp!"); checkArgument(maxTimestamp >= 0, "Precondition violation - argument 'maxTimestamp' must not be negative!"); checkArgument(maxTimestamp <= tx.getTimestamp(), "Precondition violation - argument 'maxTimestamp' must not be larger than the transaction timestamp!"); 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!"); try (AutoLock lock = this.lockNonExclusive()) { return this.getCommitMetadataStore().getCommitTimestampsPaged(minTimestamp, maxTimestamp, pageSize, pageIndex, order, includeSystemInternalCommits); } } @Override public Iterator<Entry<Long, Object>> performGetCommitMetadataPaged(final ChronoDBTransaction tx, final long minTimestamp, final long maxTimestamp, final int pageSize, final int pageIndex, final Order order, final boolean includeSystemInternalCommits) { checkNotNull(tx, "Precondition violation - argument 'tx' must not be NULL!"); checkArgument(minTimestamp >= 0, "Precondition violation - argument 'minTimestamp' must not be negative!"); checkArgument(minTimestamp <= tx.getTimestamp(), "Precondition violation - argument 'minTimestamp' must not be larger than the transaction timestamp!"); checkArgument(maxTimestamp >= 0, "Precondition violation - argument 'maxTimestamp' must not be negative!"); checkArgument(maxTimestamp <= tx.getTimestamp(), "Precondition violation - argument 'maxTimestamp' must not be larger than the transaction timestamp!"); 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!"); try (AutoLock lock = this.lockNonExclusive()) { return this.getCommitMetadataStore().getCommitMetadataPaged(minTimestamp, maxTimestamp, pageSize, pageIndex, order, includeSystemInternalCommits); } } @Override public List<Entry<Long, Object>> performGetCommitMetadataAround(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!"); try (AutoLock lock = this.lockNonExclusive()) { return this.getCommitMetadataStore().getCommitMetadataAround(timestamp, count, includeSystemInternalCommits); } } @Override public List<Entry<Long, Object>> performGetCommitMetadataBefore(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!"); try (AutoLock lock = this.lockNonExclusive()) { return this.getCommitMetadataStore().getCommitMetadataBefore(timestamp, count, includeSystemInternalCommits); } } @Override public List<Entry<Long, Object>> performGetCommitMetadataAfter(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!"); try (AutoLock lock = this.lockNonExclusive()) { return this.getCommitMetadataStore().getCommitMetadataAfter(timestamp, count, includeSystemInternalCommits); } } @Override public List<Long> performGetCommitTimestampsAround(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!"); try (AutoLock lock = this.lockNonExclusive()) { return this.getCommitMetadataStore().getCommitTimestampsAround(timestamp, count, includeSystemInternalCommits); } } @Override public List<Long> performGetCommitTimestampsBefore(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!"); try (AutoLock lock = this.lockNonExclusive()) { return this.getCommitMetadataStore().getCommitTimestampsBefore(timestamp, count, includeSystemInternalCommits); } } @Override public List<Long> performGetCommitTimestampsAfter(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!"); try (AutoLock lock = this.lockNonExclusive()) { return this.getCommitMetadataStore().getCommitTimestampsAfter(timestamp, count, includeSystemInternalCommits); } } @Override public int performCountCommitTimestampsBetween(final ChronoDBTransaction tx, final long from, final long to, final boolean includeSystemInternalCommits) { checkNotNull(tx, "Precondition violation - argument 'tx' must not be NULL!"); checkArgument(from >= 0, "Precondition violation - argument 'from' must not be negative!"); checkArgument(from <= tx.getTimestamp(), "Precondition violation - argument 'from' must not be larger than the transaction timestamp!"); checkArgument(to >= 0, "Precondition violation - argument 'to' must not be negative!"); checkArgument(to <= tx.getTimestamp(), "Precondition violation - argument 'to' must not be larger than the transaction timestamp!"); try (AutoLock lock = this.lockNonExclusive()) { return this.getCommitMetadataStore().countCommitTimestampsBetween(from, to, includeSystemInternalCommits); } } @Override public int performCountCommitTimestamps(final ChronoDBTransaction tx, final boolean includeSystemInternalCommits) { checkNotNull(tx, "Precondition violation - argument 'tx' must not be NULL!"); try (AutoLock lock = this.lockNonExclusive()) { return this.getCommitMetadataStore().countCommitTimestamps(includeSystemInternalCommits); } } @Override public Object performGetCommitMetadata(final ChronoDBTransaction tx, final long commitTimestamp) { checkNotNull(tx, "Precondition violation - argument 'tx' must not be NULL!"); checkArgument(commitTimestamp >= 0, "Precondition violation - argument 'commitTimestamp' must not be negative!"); checkArgument(commitTimestamp <= tx.getTimestamp(), "Precondition violation - argument 'commitTimestamp' must be less than or equal to the transaction timestamp!"); try (AutoLock lock = this.lockNonExclusive()) { if (this.getOwningBranch().getOrigin() != null && this.getOwningBranch().getBranchingTimestamp() >= commitTimestamp) { // ask the parent branch to resolve it ChronoDBTransaction originTx = this .createOriginBranchTx(this.getOwningBranch().getBranchingTimestamp()); return this.getOriginBranchTKVS().performGetCommitMetadata(originTx, commitTimestamp); } return this.getCommitMetadataStore().get(commitTimestamp); } } @Override public Iterator<String> performGetChangedKeysAtCommit(final ChronoDBTransaction tx, final long commitTimestamp, final String keyspace) { checkNotNull(tx, "Precondition violation - argument 'tx' must not be NULL!"); checkArgument(commitTimestamp >= 0, "Precondition violation - argument 'commitTimestamp' must not be negative!"); checkArgument(commitTimestamp <= tx.getTimestamp(), "Precondition violation - argument 'commitTimestamp' must not be larger than the transaction timestamp!"); checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); try (AutoLock lock = this.lockNonExclusive()) { if (this.getOwningBranch().getOrigin() != null && this.getOwningBranch().getBranchingTimestamp() >= commitTimestamp) { // ask the parent branch to resolve it ChronoDBTransaction originTx = this .createOriginBranchTx(this.getOwningBranch().getBranchingTimestamp()); return this.getOriginBranchTKVS().performGetChangedKeysAtCommit(originTx, commitTimestamp, keyspace); } if (this.getKeyspaces(commitTimestamp).contains(keyspace) == false) { return Collections.emptyIterator(); } return this.getMatrix(keyspace).getChangedKeysAtCommit(commitTimestamp); } } // ================================================================================================================= // DATEBACK METHODS // ================================================================================================================= @Override public int datebackPurgeEntries(final Set<TemporalKey> keys) { checkNotNull(keys, "Precondition violation - argument 'keys' must not be NULL!"); if (keys.isEmpty()) { return 0; } ListMultimap<String, TemporalKey> keyspaceToKeys = Multimaps.index(keys, TemporalKey::getKeyspace); int successfulPurges = 0; try (AutoLock lock = this.owningDB.lockExclusive()) { for (Entry<String, Collection<TemporalKey>> keyspaceToEntries : keyspaceToKeys.asMap().entrySet()) { String keyspace = keyspaceToEntries.getKey(); Collection<TemporalKey> entries = keyspaceToEntries.getValue(); TemporalDataMatrix matrix = this.getMatrix(keyspace); if (matrix == null) { // matrix doesn't exist, so entry can't exist => we're done continue; } Set<UnqualifiedTemporalKey> utks = entries.stream() .map(e -> UnqualifiedTemporalKey.create(e.getKey(), e.getTimestamp())) .collect(Collectors.toSet()); successfulPurges += matrix.purgeEntries(utks); // TODO in theory, we could implement cascading here: // - if the last entry of a commit was removed, the commit as a whole could be removed. // - if the last entry of a keyset was removed, the keyset could be removed (or at least it's creation could // be moved forward in time until the first entry is inserted) } } return successfulPurges; } @Override public Set<TemporalKey> datebackPurgeKey(final String keyspace, final String key) { checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); try (AutoLock lock = this.owningDB.lockExclusive()) { TemporalDataMatrix matrix = this.getMatrix(keyspace); if (matrix == null) { // matrix doesn't exist, so entry can't exist => we're done return Collections.emptySet(); } Collection<Long> affectedTimestamps = matrix.purgeKey(key); if (affectedTimestamps.isEmpty()) { return Collections.emptySet(); } else { // map the timestamps to temporal keys by using the fixed keyspace and key from our parameters return affectedTimestamps.stream().map(ts -> TemporalKey.create(ts, keyspace, key)) .collect(Collectors.toSet()); } } } @Override public Set<TemporalKey> datebackPurgeKey(final String keyspace, final String key, final BiPredicate<Long, Object> predicate) { checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); checkNotNull(predicate, "Precondition violation - argument 'predicate' must not be NULL!"); Set<TemporalKey> affectedKeys = Sets.newHashSet(); try (AutoLock lock = this.owningDB.lockExclusive()) { TemporalDataMatrix matrix = this.getMatrix(keyspace); if (matrix == null) { // matrix doesn't exist, so entry can't exist => we're done return Collections.emptySet(); } long now = this.getNow(); List<Long> history = Lists.newArrayList(matrix.history(key, 0, now, Order.DESCENDING)); for (long timestamp : history) { GetResult<byte[]> getResult = matrix.get(timestamp, key); byte[] serialValue = getResult.getValue(); Object deserializedObject = this.deserialize(serialValue); boolean match = predicate.test(timestamp, deserializedObject); if (match) { boolean purged = this.datebackPurgeEntry(keyspace, key, timestamp); if (purged) { affectedKeys.add(TemporalKey.create(timestamp, keyspace, key)); } } } } return affectedKeys; } @Override public Set<TemporalKey> datebackPurgeKey(final String keyspace, final String key, final long purgeRangeStart, final long purgeRangeEnd) { checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); checkArgument(purgeRangeStart >= 0, "Precondition violation - argument 'purgeRangeStart' must not be negative!"); checkArgument(purgeRangeEnd >= purgeRangeStart, "Precondition violation - argument 'purgeRangeEnd' must be greater than or equal to 'purgeRangeStart'!"); // TODO PERFORMANCE: this could be optimized, as the called method unnecessarily deserializes the value BiPredicate<Long, Object> predicate = new BiPredicate<Long, Object>() { @Override public boolean test(final Long t, final Object u) { return purgeRangeStart <= t && t <= purgeRangeEnd; } }; return this.datebackPurgeKey(keyspace, key, predicate); } @Override public Set<TemporalKey> datebackPurgeKeyspace(final String keyspace, final long purgeRangeStart, final long purgeRangeEnd) { checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkArgument(purgeRangeStart >= 0, "Precondition violation - argument 'purgeRangeStart' must not be negative!"); checkArgument(purgeRangeEnd >= purgeRangeStart, "Precondition violation - argument 'purgeRangeEnd' must be greater than or equal to 'purgeRangeStart'!"); try (AutoLock lock = this.owningDB.lockExclusive()) { TemporalDataMatrix matrix = this.getMatrix(keyspace); if (matrix == null) { // matrix doesn't exist, so entry can't exist => we're done return Collections.emptySet(); } return matrix.purgeAllEntriesInTimeRange(purgeRangeStart, purgeRangeEnd).stream() .map(utk -> utk.toTemporalKey(keyspace)) .collect(Collectors.toSet()); } } @Override public Set<TemporalKey> datebackPurgeCommit(final long commitTimestamp) { checkArgument(commitTimestamp >= 0, "Precondition violation - argument 'commitTimestamp' must not be negative!"); try (AutoLock lock = this.owningDB.lockExclusive()) { Set<String> keyspaces = this.getKeyspaces(commitTimestamp); Set<TemporalKey> keysToPurge = Sets.newHashSet(); for (String keyspace : keyspaces) { Iterator<String> keysAtCommit = this.getMatrix(keyspace).getChangedKeysAtCommit(commitTimestamp); keysAtCommit.forEachRemaining(key -> { keysToPurge.add(TemporalKey.create(commitTimestamp, keyspace, key)); }); } this.datebackPurgeEntries(keysToPurge); this.getCommitMetadataStore().purge(commitTimestamp); return keysToPurge; } } @Override public Set<TemporalKey> datebackPurgeCommits(final long purgeRangeStart, final long purgeRangeEnd) { checkArgument(purgeRangeStart >= 0, "Precondition violation - argument 'purgeRangeStart' must not be negative!"); checkArgument(purgeRangeEnd >= purgeRangeStart, "Precondition violation - argument 'purgeRangeEnd' must be greater than or equal to 'purgeRangeStart'!"); Set<TemporalKey> affectedKeys = Sets.newHashSet(); try (AutoLock lock = this.owningDB.lockExclusive()) { List<Long> commitTimestamps = Lists.newArrayList(this.getCommitMetadataStore() .getCommitTimestampsBetween(purgeRangeStart, purgeRangeEnd, Order.ASCENDING, true)); for (long commitTimestamp : commitTimestamps) { affectedKeys.addAll(this.datebackPurgeCommit(commitTimestamp)); } } return affectedKeys; } @Override public Set<TemporalKey> datebackInject(final String keyspace, final String key, final long timestamp, final Object value) { checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); Map<QualifiedKey, Object> entries = Maps.newHashMap(); entries.put(QualifiedKey.create(keyspace, key), value); return this.datebackInject(timestamp, entries, null, false); } @Override public Set<TemporalKey> datebackInject(final String keyspace, final String key, final long timestamp, final Object value, final Object commitMetadata) { checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); return this.datebackInject(keyspace, key, timestamp, value, commitMetadata, false); } @Override public Set<TemporalKey> datebackInject(final String keyspace, final String key, final long timestamp, final Object value, final Object commitMetadata, final boolean overrideCommitMetadata) { checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); Map<QualifiedKey, Object> entries = Maps.newHashMap(); entries.put(QualifiedKey.create(keyspace, key), value); return this.datebackInject(timestamp, entries, commitMetadata, overrideCommitMetadata); } @Override public Set<TemporalKey> datebackInject(final long timestamp, final Map<QualifiedKey, Object> entries) { checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); checkNotNull(entries, "Precondition violation - argument 'entries' must not be NULL!"); return this.datebackInject(timestamp, entries, null, false); } @Override public Set<TemporalKey> datebackInject(final long timestamp, final Map<QualifiedKey, Object> entries, final Object commitMetadata) { checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); checkNotNull(entries, "Precondition violation - argument 'entries' must not be NULL!"); return this.datebackInject(timestamp, entries, commitMetadata, false); } @Override public Set<TemporalKey> datebackInject(final long timestamp, final Map<QualifiedKey, Object> entries, final Object commitMetadata, final boolean overrideCommitMetadata) { checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); checkNotNull(entries, "Precondition violation - argument 'entries' must not be NULL!"); Set<ChronoDBEntry> dbEntries = Sets.newHashSet(); String branch = this.getOwningBranch().getName(); for (Entry<QualifiedKey, Object> entry : entries.entrySet()) { QualifiedKey qualifiedKey = entry.getKey(); Object value = entry.getValue(); byte[] serialized = this.serialize(value); ChronoIdentifier chronoIdentifier = ChronoIdentifier.create(branch, timestamp, qualifiedKey); ChronoDBEntry dbEntry = ChronoDBEntry.create(chronoIdentifier, serialized); dbEntries.add(dbEntry); } this.insertEntries(dbEntries, true); // check if we either don't have a commit at this timestamp in the commit log, or we should override the // metadata if (this.getCommitMetadataStore().hasCommitAt(timestamp) == false || overrideCommitMetadata) { this.getCommitMetadataStore().put(timestamp, commitMetadata); } // we (defensively) assume here that all db entries have indeed been changed Set<TemporalKey> changedKeys = dbEntries.stream().map(e -> e.getIdentifier().toTemporalKey()) .collect(Collectors.toSet()); return changedKeys; } @Override public Set<TemporalKey> datebackTransformEntry(final String keyspace, final String key, final long timestamp, final Function<Object, Object> transformation) { checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); checkNotNull(transformation, "Precondition violation - argument 'transformation' must not be NULL!"); TemporalDataMatrix matrix = this.getMatrix(keyspace); if (matrix == null) { // matrix doesn't exist -> we are done return Collections.emptySet(); } UnqualifiedTemporalEntry entry = this.readAndTransformSingleEntryInMemory(keyspace, key, timestamp, transformation); if (entry == null) { // transformation function stated that the entry is unchanged return Collections.emptySet(); } matrix.insertEntries(Collections.singleton(entry), true); return Collections.singleton(TemporalKey.create(timestamp, keyspace, key)); } public Set<TemporalKey> datebackTransformEntries(final Set<TemporalKey> keys, final BiFunction<TemporalKey, Object, Object> valueTransformation) { checkNotNull(keys, "Precondition violation - argument 'keys' must not be NULL!"); checkNotNull(valueTransformation, "Precondition violation - argument 'valueTransformation' must not be NULL!"); if (keys.isEmpty()) { return Collections.emptySet(); } ListMultimap<String, TemporalKey> keyspaceToKeys = Multimaps.index(keys, key -> key.getKeyspace()); Set<TemporalKey> resultSet = Sets.newHashSet(); for (Entry<String, Collection<TemporalKey>> keyspaceToKeysEntry : keyspaceToKeys.asMap().entrySet()) { String keyspace = keyspaceToKeysEntry.getKey(); Collection<TemporalKey> localKeys = keyspaceToKeysEntry.getValue(); TemporalDataMatrix matrix = this.getMatrix(keyspace); if (matrix == null) { // matrix doesn't exist -> we are done in this keyspace continue; } Set<UnqualifiedTemporalEntry> transformedEntries = localKeys.stream().map(localKey -> this.readAndTransformSingleEntryInMemory( keyspace, localKey.getKey(), localKey.getTimestamp(), (oldValue) -> valueTransformation.apply(localKey, oldValue) ) ).filter(java.util.Objects::nonNull).collect(Collectors.toSet()); matrix.insertEntries(transformedEntries, true); resultSet.addAll(transformedEntries.stream().map(UnqualifiedTemporalEntry::getKey).map(utk -> utk.toTemporalKey(keyspace)).collect(Collectors.toSet())); } return resultSet; } @Override public Set<TemporalKey> datebackTransformValuesOfKey(final String keyspace, final String key, final BiFunction<Long, Object, Object> transformation) { checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); checkNotNull(transformation, "Precondition violation - argument 'transformation' must not be NULL!"); TemporalDataMatrix matrix = this.getMatrix(keyspace); if (matrix == null) { // matrix doesn't exist -> we are done return Collections.emptySet(); } int maxBatchSize = 1000; // we batch this operation internally in order to prevent out-of-memory issues Set<UnqualifiedTemporalEntry> newEntries = Sets.newHashSet(); Set<TemporalKey> modifiedKeys = Sets.newHashSet(); Iterator<Long> localHistory = matrix.history(key, 0, this.getNow(), Order.DESCENDING); while (localHistory.hasNext()) { long timestamp = localHistory.next(); UnqualifiedTemporalEntry entry = this.readAndTransformSingleEntryInMemory(keyspace, key, timestamp, (oldVal) -> transformation.apply(timestamp, oldVal)); if (entry == null) { // transformation stated that the entry is unchanged continue; } newEntries.add(entry); if (newEntries.size() >= maxBatchSize) { // flush this batch of entries back into the matrix matrix.insertEntries(newEntries, true); modifiedKeys.addAll( newEntries.stream().map(e -> TemporalKey.create(e.getKey().getTimestamp(), keyspace, key)) .collect(Collectors.toSet())); newEntries.clear(); } } // flush the entries which remain in our batch if (newEntries.isEmpty() == false) { matrix.insertEntries(newEntries, true); modifiedKeys .addAll(newEntries.stream().map(e -> TemporalKey.create(e.getKey().getTimestamp(), keyspace, key)) .collect(Collectors.toSet())); } return modifiedKeys; } @Override public Set<TemporalKey> datebackTransformCommit(final long commitTimestamp, final Function<Map<QualifiedKey, Object>, Map<QualifiedKey, Object>> transformation) { checkArgument(commitTimestamp >= 0, "Precondition violation - argument 'commitTimestamp' must not be negative!"); checkNotNull(transformation, "Precondition violation - argument 'transformation' must not be NULL!"); // fetch the data contained in the commit Set<String> keyspaces = this.getKeyspaces(commitTimestamp); Map<QualifiedKey, Object> commitContent = Maps.newHashMap(); for (String keyspace : keyspaces) { TemporalDataMatrix matrix = this.getMatrix(keyspace); if (matrix == null) { // we have no matrix, so we certainly have no commit continue; } Iterator<String> changedKeysAtCommit = matrix.getChangedKeysAtCommit(commitTimestamp); changedKeysAtCommit.forEachRemaining(key -> { GetResult<byte[]> getResult = this.readEntryAtCoordinates(keyspace, key, commitTimestamp); if (getResult == null) { throw new IllegalStateException("Failed to read entry of commit!"); } Object value = this.deserialize(getResult.getValue()); commitContent.put(QualifiedKey.create(keyspace, key), value); }); } // apply the transformation in-memory Map<QualifiedKey, Object> transformedMap = transformation.apply(Collections.unmodifiableMap(commitContent)); // check if we lost some entries Set<TemporalKey> removedKeys = commitContent.keySet().stream() .filter(key -> transformedMap.containsKey(key) == false) .map(key -> TemporalKey.create(commitTimestamp, key.getKeyspace(), key.getKey())) .collect(Collectors.toSet()); this.datebackPurgeEntries(removedKeys); // inject the entries which are new Map<QualifiedKey, Object> addedEntries = Maps.filterEntries(transformedMap, entry -> commitContent.containsKey(entry.getKey()) == false); this.datebackInject(commitTimestamp, addedEntries); // transform the values of the remaining entries Map<TemporalKey, Object> temporalKeyToNewValue = Maps.newHashMap(); transformedMap.entrySet().stream() // consider only the entries which are contained in the transformed commit .filter(e -> commitContent.containsKey(e.getKey())) // ignore entries which are flagged as unchanged .filter(e -> e.getValue() != Dateback.UNCHANGED) // construct temporal keys from the qualified keys to ensure the lower-level API matches .forEach(e -> { QualifiedKey qKey = e.getKey(); TemporalKey tKey = TemporalKey.create(commitTimestamp, qKey.getKeyspace(), qKey.getKey()); temporalKeyToNewValue.put(tKey, e.getValue()); }); this.datebackTransformEntries(temporalKeyToNewValue.keySet(), (key, oldValue) -> temporalKeyToNewValue.get(key)); Set<TemporalKey> changedTemporalKeys = Sets.newHashSet(); changedTemporalKeys.addAll(removedKeys); for (QualifiedKey addedKey : addedEntries.keySet()) { changedTemporalKeys.add(TemporalKey.create(commitTimestamp, addedKey)); } changedTemporalKeys.addAll(temporalKeyToNewValue.keySet()); return changedTemporalKeys; } @Override public Collection<TemporalKey> datebackTransformValuesOfKeyspace(final String keyspace, final KeyspaceValueTransformation valueTransformation) { TemporalDataMatrix matrix = this.getMatrix(keyspace); if (matrix == null) { // the keyspace doesn't exist... return Collections.emptySet(); } // TODO The code below is not very efficient if a lot of values change; the collection holding // the new data could grow to considerable sizes. However, it is the easiest way to implement this for now. Set<UnqualifiedTemporalEntry> newEntries = Sets.newHashSet(); CloseableIterator<UnqualifiedTemporalEntry> iterator = matrix.allEntriesIterator(this.owningBranch.getBranchingTimestamp(), Long.MAX_VALUE); try { while (iterator.hasNext()) { UnqualifiedTemporalEntry entry = iterator.next(); UnqualifiedTemporalKey temporalKey = entry.getKey(); String key = temporalKey.getKey(); long timestamp = temporalKey.getTimestamp(); Object oldValue = this.deserialize(entry.getValue()); if (oldValue == null) { // do not alter deletion markers continue; } Object newValue = valueTransformation.transformValue(key, timestamp, oldValue); if (newValue == null) { throw new IllegalStateException("KeyspaceValueTransform unexpectedly returned NULL! It is not allowed to delete values!"); } if (newValue == Dateback.UNCHANGED) { // do not change this entry continue; } UnqualifiedTemporalEntry newEntry = new UnqualifiedTemporalEntry(temporalKey, this.serialize(newValue)); newEntries.add(newEntry); } } finally { iterator.close(); } matrix.insertEntries(newEntries, true); return newEntries.stream().map(UnqualifiedTemporalEntry::getKey).map(k -> k.toTemporalKey(keyspace)).collect(Collectors.toSet()); } @Override public void datebackUpdateCommitMetadata(final long commitTimestamp, final Object newMetadata) { checkArgument(commitTimestamp >= 0, "Precondition violation - argument 'commitTimestamp' must not be negative!"); if (this.getCommitMetadataStore().hasCommitAt(commitTimestamp) == false) { throw new DatebackException("Cannot update commit metadata at timestamp " + commitTimestamp + ", because no commit has occurred there."); } this.getCommitMetadataStore().put(commitTimestamp, newMetadata); } @Override public void datebackCleanup(final String branch, long earliestTouchedTimestamp) { // in the basic implementation, we have nothing to do. Subclasses may override to perform backend-specific // cleanups for the given keys. } // ================================================================================================================= // DUMP METHODS // ================================================================================================================= @Override public CloseableIterator<ChronoDBEntry> allEntriesIterator(final long minTimestamp, final long maxTimestamp) { checkArgument(minTimestamp >= 0, "Precondition violation - argument 'minTimestamp' must not be negative!"); checkArgument(maxTimestamp >= 0, "Precondition violation - argument 'maxTimestamp' must not be negative!"); checkArgument(minTimestamp <= maxTimestamp, "Precondition violation - argument 'minTimestamp' must be less than or equal to 'maxTimestamp'!"); try (AutoLock lock = this.lockNonExclusive()) { return new AllEntriesIterator(minTimestamp, maxTimestamp); } } @Override public void insertEntries(final Set<ChronoDBEntry> entries, final boolean force) { try (AutoLock lock = this.lockBranchExclusive()) { // insertion of entries can (potentially) completely wreck the consistency of our cache. // in order to be safe, we clear it completely. this.getCache().clear(); long now = 0L; try { now = this.getNow(); } catch (Exception e) { // could not determine NOW timestamp -> we're loading a backup } long maxTimestamp = now; long branchingTimestamp = this.getOwningBranch().getBranchingTimestamp(); SetMultimap<String, UnqualifiedTemporalEntry> keyspaceToEntries = HashMultimap.create(); for (ChronoDBEntry entry : entries) { ChronoIdentifier chronoIdentifier = entry.getIdentifier(); String keyspace = chronoIdentifier.getKeyspace(); String key = chronoIdentifier.getKey(); long timestamp = chronoIdentifier.getTimestamp(); if (timestamp > System.currentTimeMillis()) { throw new IllegalArgumentException( "Cannot insert entries into database; at least one entry references a timestamp greater than the current system time!"); } if (timestamp < branchingTimestamp) { throw new IllegalArgumentException( "Cannot insert entries into database; at least one entry references a timestamp smaller than the branching timestamp of this branch!"); } byte[] value = entry.getValue(); UnqualifiedTemporalKey unqualifiedKey = new UnqualifiedTemporalKey(key, timestamp); UnqualifiedTemporalEntry unqualifiedEntry = new UnqualifiedTemporalEntry(unqualifiedKey, value); keyspaceToEntries.put(keyspace, unqualifiedEntry); maxTimestamp = Math.max(timestamp, maxTimestamp); } for (String keyspace : keyspaceToEntries.keySet()) { Set<UnqualifiedTemporalEntry> entriesToInsert = keyspaceToEntries.get(keyspace); if (entriesToInsert == null || entriesToInsert.isEmpty()) { continue; } long minTimestamp = entriesToInsert.stream().mapToLong(entry -> entry.getKey().getTimestamp()).min() .orElse(0L); TemporalDataMatrix matrix = this.getOrCreateMatrix(keyspace, minTimestamp); matrix.insertEntries(entriesToInsert, force); } if (maxTimestamp > now) { this.setNow(maxTimestamp); } } } public void updateCreationTimestampForKeyspace(String keyspaceName, long creationTimestamp) { checkNotNull(keyspaceName, "Precondition violation - argument 'keyspaceName' must not be NULL!"); checkArgument(creationTimestamp >= 0, "Precondition violation - argument 'creationTimestamp' must not be negative!"); TemporalDataMatrix matrix = this.getMatrix(keyspaceName); if (matrix != null) { matrix.ensureCreationTimestampIsGreaterThanOrEqualTo(creationTimestamp); } } // ================================================================================================================= // DEBUG METHODS // ================================================================================================================= @Override public void setDebugCallbackBeforePrimaryIndexUpdate(final Consumer<ChronoDBTransaction> action) { this.debugCallbackBeforePrimaryIndexUpdate = action; } @Override public void setDebugCallbackBeforeSecondaryIndexUpdate(final Consumer<ChronoDBTransaction> action) { this.debugCallbackBeforeSecondaryIndexUpdate = action; } @Override public void setDebugCallbackBeforeMetadataUpdate(final Consumer<ChronoDBTransaction> action) { this.debugCallbackBeforeMetadataUpdate = action; } @Override public void setDebugCallbackBeforeCacheUpdate(final Consumer<ChronoDBTransaction> action) { this.debugCallbackBeforeCacheUpdate = action; } @Override public void setDebugCallbackBeforeNowTimestampUpdate(final Consumer<ChronoDBTransaction> action) { this.debugCallbackBeforeNowTimestampUpdate = action; } @Override public void setDebugCallbackBeforeTransactionCommitted(final Consumer<ChronoDBTransaction> action) { this.debugCallbackBeforeTransactionCommitted = action; } // ================================================================================================================= // INTERNAL HELPER METHODS // ================================================================================================================= private ChronoDBCache getCache() { return this.owningDB.getCache(); } @Override protected void verifyTransaction(final ChronoDBTransaction tx) { if (tx.getTimestamp() > this.getNow()) { throw new InvalidTransactionTimestampException( "Transaction timestamp (" + tx.getTimestamp() + ") must not be greater than timestamp of last commit (" + this.getNow() + ") on branch '" + this.getOwningBranch().getName() + "'!"); } if (this.getOwningDB().getBranchManager().existsBranch(tx.getBranchName()) == false) { throw new InvalidTransactionBranchException( "The branch '" + tx.getBranchName() + "' does not exist at timestamp '" + tx.getTimestamp() + "'!"); } } protected AtomicConflict scanForConflict(final ChronoDBTransaction tx, final long transactionCommitTimestamp, final String keyspace, final String key, final Object value) { Set<String> keyspaces = this.getKeyspaces(transactionCommitTimestamp); long now = this.getNow(); if (tx.getTimestamp() == now) { // this transaction was started at the "now" timestamp. There has not been any commit // between starting this transaction and the current state. Therefore, there cannot // be any conflicts. return null; } if (keyspaces.contains(keyspace) == false) { // the keyspace is new, so blind overwrite can't happen return null; } // get the matrix representing the keyspace TemporalDataMatrix matrix = this.getMatrix(keyspace); if (matrix == null) { // the keyspace didn't even exist before, so no conflicts can happen return null; } // check when the last commit on that key has occurred long lastCommitTimestamp = -1; Object targetValue = null; String branch = tx.getBranchName(); QualifiedKey qKey = QualifiedKey.create(keyspace, key); // first, try to find it in the cache CacheGetResult<Object> cacheGetResult = this.getCache().get(branch, now, qKey); if (cacheGetResult.isHit()) { // use the values from the cache lastCommitTimestamp = cacheGetResult.getValidFrom(); targetValue = cacheGetResult.getValue(); } else { // not in cache, load from store GetResult<?> getResult = this.performRangedGetInternal(branch, qKey, now, false); if (getResult.isHit()) { lastCommitTimestamp = getResult.getPeriod().getLowerBound(); targetValue = getResult.getValue(); } } // if the last commit timestamp was after our transaction, we have a potential conflict if (lastCommitTimestamp > tx.getTimestamp()) { ChronoIdentifier sourceKey = ChronoIdentifier.create(branch, transactionCommitTimestamp, qKey); ChronoIdentifier targetKey = ChronoIdentifier.create(branch, lastCommitTimestamp, qKey); return new AtomicConflictImpl(tx.getTimestamp(), sourceKey, value, targetKey, targetValue, this::findCommonAncestor); } // not conflicting return null; } /** * Returns the {@link TemporalDataMatrix} responsible for the given keyspace. * * @param keyspace The name of the keyspace to get the matrix for. Must not be <code>null</code>. * @return The temporal data matrix that stores the keyspace data, or <code>null</code> if there is no keyspace for * the given name. */ public TemporalDataMatrix getMatrix(final String keyspace) { checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); return this.keyspaceToMatrix.get(keyspace); } /** * Returns the {@link TemporalDataMatrix} responsible for the given keyspace, creating it if it does not exist. * * @param keyspace The name of the keyspace to get the matrix for. Must not be <code>null</code>. * @param timestamp In case of a "create", this timestamp specifies the creation timestamp of the matrix. Must not be * negative. * @return The temporal data matrix that stores the keyspace data. Never <code>null</code>. */ protected TemporalDataMatrix getOrCreateMatrix(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!"); TemporalDataMatrix matrix = this.getMatrix(keyspace); if (matrix == null) { matrix = this.createMatrix(keyspace, timestamp); this.keyspaceToMatrix.put(keyspace, matrix); } return matrix; } protected void writeCommitThroughCache(final String branchName, final long timestamp, final Map<String, Map<String, Object>> keyspaceToKeyToValue) { // perform the write-through in our cache Map<QualifiedKey, Object> keyValues = Maps.newHashMap(); boolean assumeImmutableValues = this.getOwningDB().getConfiguration().isAssumeCachedValuesAreImmutable(); for (Entry<String, Map<String, Object>> outerEntry : keyspaceToKeyToValue.entrySet()) { String keyspace = outerEntry.getKey(); Map<String, Object> keyToValue = outerEntry.getValue(); for (Entry<String, Object> innerEntry : keyToValue.entrySet()) { String key = innerEntry.getKey(); Object value = innerEntry.getValue(); if (assumeImmutableValues == false) { // values are not immutable, so we add a copy to the cache to prevent modification from outside value = KryoManager.deepCopy(value); } QualifiedKey qKey = QualifiedKey.create(keyspace, key); keyValues.put(qKey, value); } } this.getCache().writeThrough(branchName, timestamp, keyValues); } @VisibleForTesting public void performRollbackToTimestamp(final long timestamp, final Set<String> modifiedKeyspaces, final boolean touchedIndex) { checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); checkNotNull(modifiedKeyspaces, "Precondition violation - argument 'modifiedKeyspaces' must not be NULL!"); for (String keyspace : modifiedKeyspaces) { TemporalDataMatrix matrix = this.getMatrix(keyspace); if (matrix != null) { matrix.rollback(timestamp); } } // roll back the commit metadata store this.getCommitMetadataStore().rollbackToTimestamp(timestamp); // roll back the cache this.getCache().rollbackToTimestamp(timestamp); // only rollback the index manager if we touched it during the commit if (touchedIndex) { this.getOwningDB().getIndexManager().rollback(this.getOwningBranch(), timestamp); } this.setNow(timestamp); } protected void assertThatTransactionMayPerformIncrementalCommit(final ChronoDBTransaction tx) { synchronized (this.incrementalCommitLock) { if (this.incrementalCommitTransaction == null) { // nobody is currently performing an incremental commit, this means // that the given transaction may start an incremental commit process. return; } else { // we have an ongoing incremental commit process. This means that only // the transaction that started this process may continue to perform // incremental commits, all other transactions are not allowed to // commit incrementally before the running process is terminated. if (this.incrementalCommitTransaction == tx) { // it is the same transaction that started the process, // therefore it may continue to perform incremental commits. return; } else { // an incremental commit process is running, but it is controlled // by a different transaction. Therefore, this transaction must not // perform incremental commits. throw new ChronoDBCommitException( "An incremental commit process is already being executed by another transaction. " + "Only one incremental commit process may be active at a given time, " + "therefore this incremental commit is rejected."); } } } } protected void assertThatTransactionMayPerformCommit(final ChronoDBTransaction tx) { synchronized (this.incrementalCommitLock) { if (this.incrementalCommitTransaction == null) { // no incremental commit is going on; accept the regular commit return; } else { // an incremental commit is occurring. Only accept a full commit from // the transaction that started the incremental commit process. if (this.incrementalCommitTransaction == tx) { // this is the transaction that started the incremental commit process, // therefore it may perform the terminating commit return; } else { // an incremental commit process is going on, started by a different // transaction. Reject this commit. throw new ChronoDBCommitException( "An incremental commit process is currently being executed by another transaction. " + "Commits from other transasctions cannot be accepted while an incremental commit process is active, " + "therefore this commit is rejected."); } } } } protected boolean isFirstIncrementalCommit(final ChronoDBTransaction tx) { synchronized (this.incrementalCommitLock) { if (this.incrementalCommitTimestamp > 0) { // the incremental commit timestamp has already been decided -> this cannot be the first incremental // commit return false; } else { // the incremental commit timestamp has not yet been decided -> this is the first incremental commit return true; } } } protected void setUpIncrementalCommit(final ChronoDBTransaction tx) { synchronized (this.incrementalCommitLock) { this.incrementalCommitTimestamp = System.currentTimeMillis(); // make sure we do not write to the same timestamp twice while (this.incrementalCommitTimestamp <= this.getNow()) { try { Thread.sleep(1); } catch (InterruptedException ignored) { // raise the interrupt flag again Thread.currentThread().interrupt(); } this.incrementalCommitTimestamp = System.currentTimeMillis(); } this.incrementalCommitTransaction = tx; } } protected void terminateIncrementalCommitProcess() { synchronized (this.incrementalCommitLock) { this.incrementalCommitTimestamp = -1L; this.incrementalCommitTransaction = null; } } protected boolean isIncrementalCommitProcessOngoing() { synchronized (this.incrementalCommitLock) { if (this.incrementalCommitTimestamp >= 0) { return true; } else { return false; } } } protected boolean isMasterBranchTKVS() { return this.owningBranch.getOrigin() == null; } protected TemporalKeyValueStore getOriginBranchTKVS() { return ((BranchInternal) this.owningBranch.getOrigin()).getTemporalKeyValueStore(); } protected ChronoDBTransaction createOriginBranchTx(final long requestedTimestamp) { long branchingTimestamp = this.owningBranch.getBranchingTimestamp(); long timestamp = 0; if (requestedTimestamp > branchingTimestamp) { // the requested timestamp is AFTER our branching timestamp. Therefore, we must // hide any changes in the parent branch that happened after the branching. To // do so, we redirect to the branching timestamp. timestamp = branchingTimestamp; } else { // the requested timestamp is BEFORE our branching timestamp. This means that we // do not need to mask any changes in our parent branch, and can therefore continue // to use the same request timestamp. timestamp = requestedTimestamp; } MutableTransactionConfiguration txConfig = new DefaultTransactionConfiguration(); txConfig.setBranch(this.owningBranch.getOrigin().getName()); txConfig.setTimestamp(timestamp); // origin branch transactions are always deliberately in the past, therefore always readonly. txConfig.setReadOnly(true); // queries on the origin branch are always allowed during dateback txConfig.setAllowedDuringDateback(true); return this.owningDB.tx(txConfig); } protected Pair<ChronoIdentifier, Object> findCommonAncestor(final long transactionTimestamp, final ChronoIdentifier source, final ChronoIdentifier target) { checkArgument(transactionTimestamp >= 0, "Precondition violation - argument 'transactionTimestamp' must not be negative!"); checkNotNull(source, "Precondition violation - argument 'source' must not be NULL!"); checkNotNull(target, "Precondition violation - argument 'target' must not be NULL!"); checkArgument(source.toQualifiedKey().equals(target.toQualifiedKey()), "Precondition violation - arguments 'source' and 'target' do not specify the same qualified key, so there cannot be a common ancestor!"); // perform a GET on the coordinates of the target, at the transaction timestamp of the inserting transaction GetResult<?> getResult = this.performRangedGetInternal(target.getBranchName(), target.toQualifiedKey(), transactionTimestamp, false); if (getResult.isHit() == false) { // no common ancestor return null; } long ancestorTimestamp = getResult.getPeriod().getLowerBound(); // TODO: this is technically correct: if B branches away from A, then every entry in A is also // an entry in B. However, some client code might expect to see branch A here if the timestamp // is before the branching timestamp of B... String ancestorBranch = target.getBranchName(); QualifiedKey ancestorQKey = getResult.getRequestedKey(); ChronoIdentifier ancestorIdentifier = ChronoIdentifier.create(ancestorBranch, TemporalKey.create(ancestorTimestamp, ancestorQKey)); Object ancestorValue = getResult.getValue(); return Pair.of(ancestorIdentifier, ancestorValue); } @Override public BranchHeadStatistics calculateBranchHeadStatistics() { long now = this.getNow(); long totalHead = 0; long totalHistory = 0; for (String keyspace : this.getKeyspaces(now)) { Set<String> keySet = this.performKeySet(this.getOwningBranch().getName(), now, keyspace); long headEntries = keySet.size(); TemporalDataMatrix matrix = this.getMatrix(keyspace); long historyEntries; if (matrix == null) { historyEntries = 0; } else { historyEntries = matrix.size(); } totalHead += headEntries; totalHistory += historyEntries; } return new BranchHeadStatisticsImpl(totalHead, totalHistory); } // ================================================================================================================= // COMMIT HELPERS // ================================================================================================================= private long waitForNextValidCommitTimestamp() { // make sure we do not write to the same timestamp twice return this.owningDB.getCommitTimestampProvider().getNextCommitTimestamp(this.getNow()); } private ChangeSet analyzeChangeSet( final ChronoDBTransaction tx, final ChronoDBTransaction oldValueTx, final long time ) { ChangeSet changeSet = new ChangeSet(); boolean duplicateVersionEliminationEnabled = tx.getConfiguration().getDuplicateVersionEliminationMode() .equals(DuplicateVersionEliminationMode.ON_COMMIT); ConflictResolutionStrategy conflictResolutionStrategy = tx.getConfiguration().getConflictResolutionStrategy(); for (ChangeSetEntry entry : tx.getChangeSet()) { String keyspace = entry.getKeyspace(); String key = entry.getKey(); Object newValue = entry.getValue(); Object oldValue = oldValueTx.get(keyspace, key); Set<PutOption> options = entry.getOptions(); // conflict checking is not supported in incremental commit mode if (this.isIncrementalCommitProcessOngoing() == false) { if (duplicateVersionEliminationEnabled) { if (Objects.equal(oldValue, newValue)) { // the new value is identical to the old one -> ignore it continue; } } // check if conflicting with existing entry AtomicConflict conflict = this.scanForConflict(tx, time, keyspace, key, newValue); if (conflict != null) { // resolve conflict newValue = conflictResolutionStrategy.resolve(conflict); // eliminate duplicates after resolving the conflict if (Objects.equal(conflict.getTargetValue(), newValue)) { // objects are identical after resolve, no need to commit the entry continue; } // the "old value" is the previous value of our target now, because // this is the timeline we merge into oldValue = conflict.getTargetValue(); } } if (entry.isRemove()) { changeSet.addEntry(keyspace, key, null); } else { changeSet.addEntry(keyspace, key, newValue); } ChronoIdentifier identifier = ChronoIdentifier.create(this.getOwningBranch(), time, keyspace, key); if (options.contains(PutOption.NO_INDEX) == false) { changeSet.addEntryToIndex(identifier, oldValue, newValue); } } return changeSet; } private void updatePrimaryIndex(String perfLogPrefix, final long time, final ChangeSet changeSet) { boolean performanceLoggingActive = this.owningDB.getConfiguration().isCommitPerformanceLoggingActive(); SerializationManager serializer = this.getOwningDB().getSerializationManager(); long beforeSerialization = System.currentTimeMillis(); Iterable<Entry<String, Map<String, byte[]>>> serializedChangeSet = changeSet .getSerializedEntriesByKeyspace(serializer::serialize); if (performanceLoggingActive) { log.info(perfLogPrefix + " -> Serialize ChangeSet (" + changeSet.size() + "): " + (System.currentTimeMillis() - beforeSerialization) + "ms."); } for (Entry<String, Map<String, byte[]>> entry : serializedChangeSet) { String keyspace = entry.getKey(); Map<String, byte[]> contents = entry.getValue(); long beforeGetMatrix = System.currentTimeMillis(); TemporalDataMatrix matrix = this.getOrCreateMatrix(keyspace, time); if (performanceLoggingActive) { log.info(perfLogPrefix + " -> Get Matrix for keyspace [" + keyspace + "]: " + (System.currentTimeMillis() - beforeGetMatrix) + "ms."); } long beforePut = System.currentTimeMillis(); matrix.put(time, contents); if (performanceLoggingActive) { log.info(perfLogPrefix + " -> Put ChangeSet (" + changeSet.size() + ") into keyspace [" + keyspace + "]: " + (System.currentTimeMillis() - beforePut) + "ms."); } } } private boolean updateSecondaryIndices(final ChangeSet changeSet) { IndexManagerInternal indexManager = this.getOwningDB().getIndexManager(); if (indexManager != null) { if (this.isIncrementalCommitProcessOngoing()) { // clear the query cache (if any). The reason for this is that during incremental updates, // we can get different results for the same query on the same timestamp. This is due to // changes in the same key at the timestamp of the incremental commit process. indexManager.clearQueryCache(); // roll back the changed keys to the state before the incremental commit started Set<QualifiedKey> modifiedKeys = changeSet.getModifiedKeys(); indexManager.rollback(this.getOwningBranch(), this.getNow(), modifiedKeys); } // re-index the modified keys indexManager.index(changeSet.getEntriesToIndex()); return true; } // no secondary index manager present return false; } private void rollbackCurrentCommit(final ChangeSet changeSet, final boolean touchedIndex) { WriteAheadLogToken walToken = this.getWriteAheadLogTokenIfExists(); Set<String> keyspaces = null; if (this.isIncrementalCommitProcessOngoing()) { // we are committing incrementally, no one knows which keyspaces were touched, // so we roll them all back just to be safe keyspaces = this.getAllKeyspaces(); } else { // in a regular commit, only the keyspaces in our current transaction were touched keyspaces = changeSet.getModifiedKeyspaces(); } this.performRollbackToTimestamp(walToken.getNowTimestampBeforeCommit(), keyspaces, touchedIndex); if (this.isIncrementalCommitProcessOngoing()) { // as a safety measure, we also have to clear the cache this.getCache().clear(); // terminate the incremental commit process this.terminateIncrementalCommitProcess(); } // after rolling back, we can clear the write ahead log this.clearWriteAheadLogToken(); } // ================================================================================================================= // DEBUG CALLBACKS // ================================================================================================================= protected void debugCallbackBeforePrimaryIndexUpdate(final ChronoDBTransaction tx) { if (this.getOwningDB().getConfiguration().isDebugModeEnabled() == false) { return; } if (this.debugCallbackBeforePrimaryIndexUpdate != null) { this.debugCallbackBeforePrimaryIndexUpdate.accept(tx); } } protected void debugCallbackBeforeSecondaryIndexUpdate(final ChronoDBTransaction tx) { if (this.getOwningDB().getConfiguration().isDebugModeEnabled() == false) { return; } if (this.debugCallbackBeforeSecondaryIndexUpdate != null) { this.debugCallbackBeforeSecondaryIndexUpdate.accept(tx); } } protected void debugCallbackBeforeMetadataUpdate(final ChronoDBTransaction tx) { if (this.getOwningDB().getConfiguration().isDebugModeEnabled() == false) { return; } if (this.debugCallbackBeforeMetadataUpdate != null) { this.debugCallbackBeforeMetadataUpdate.accept(tx); } } protected void debugCallbackBeforeCacheUpdate(final ChronoDBTransaction tx) { if (this.getOwningDB().getConfiguration().isDebugModeEnabled() == false) { return; } if (this.debugCallbackBeforeCacheUpdate != null) { this.debugCallbackBeforeCacheUpdate.accept(tx); } } protected void debugCallbackBeforeNowTimestampUpdate(final ChronoDBTransaction tx) { if (this.getOwningDB().getConfiguration().isDebugModeEnabled() == false) { return; } if (this.debugCallbackBeforeNowTimestampUpdate != null) { this.debugCallbackBeforeNowTimestampUpdate.accept(tx); } } protected void debugCallbackBeforeTransactionCommitted(final ChronoDBTransaction tx) { if (this.getOwningDB().getConfiguration().isDebugModeEnabled() == false) { return; } if (this.debugCallbackBeforeTransactionCommitted != null) { this.debugCallbackBeforeTransactionCommitted.accept(tx); } } protected Object deserialize(final byte[] serialForm) { Object deserializedValue; if (serialForm == null || serialForm.length <= 0) { deserializedValue = null; } else { deserializedValue = this.getOwningDB().getSerializationManager().deserialize(serialForm); } return deserializedValue; } protected byte[] serialize(final Object object) { if (object == null) { return new byte[0]; } return this.getOwningDB().getSerializationManager().serialize(object); } /** * Reads the entry at the given (exact) coordinates * * @param keyspace The keyspace of the entry to retrieve. Must not be <code>null</code>. * @param key The key of the entry to retrieve. Must not be <code>null</code>. * @param timestamp The exact timestamp of the entry to retrieve. Must not be <code>null</code>. * @return The {@link GetResult} of the operation, or <code>null</code> if the specified matrix cell is empty. */ private GetResult<byte[]> readEntryAtCoordinates(final String keyspace, final String key, final long timestamp) { checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); TemporalDataMatrix matrix = this.getMatrix(keyspace); GetResult<byte[]> getResult = matrix.get(timestamp, key); if (getResult.isHit() == false || getResult.getPeriod().getLowerBound() != timestamp) { return null; } return getResult; } /** * Reads the entry at the given coordinates from the matrix and applies the given transformation. * * <p> * Important note: the entry will <b>not</b> be written back into the matrix after the transformation. However, the * caller is free to do so if desired. * * @param keyspace The keyspace of the entry to retrieve and transform. Must not be <code>null</code>. * @param key The key of the entry to retrieve and transform. Must not be <code>null</code>. * @param timestamp The timestamp of the entry to retrieve and transform. Must match the entry <b>exactly</b>. Must not be * negative. * @param transformation The transformation to apply. Must not be <code>null</code>, must be a pure function. The function * receives the old value (which may be <code>null</code>, indicating that the entry is a deletion) and * returns the new value (again, <code>null</code> indicates a deletion). The function may also return * {@link Dateback#UNCHANGED} to indicate that the old value should not change. * @return The modified unqualified temporal entry, or <code>null</code> if the transformation function returned * {@link Dateback#UNCHANGED}. */ private UnqualifiedTemporalEntry readAndTransformSingleEntryInMemory(final String keyspace, final String key, final long timestamp, final Function<Object, Object> transformation) { checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); checkNotNull(transformation, "Precondition violation - argument 'transformation' must not be NULL!"); GetResult<byte[]> getResult = this.readEntryAtCoordinates(keyspace, key, timestamp); if (getResult == null) { // the requested transformation cannot take place because there is no entry at the given coordinates throw new DatebackException("Cannot execute transformation: there is no entry at [" + this.getOwningBranch().getName() + "->" + keyspace + "->" + key + "@" + timestamp + "]!"); } Object oldValue = this.deserialize(getResult.getValue()); Object newValue = transformation.apply(oldValue); if (newValue == Dateback.UNCHANGED) { return null; } byte[] serializedNewValue = this.serialize(newValue); UnqualifiedTemporalEntry entry = new UnqualifiedTemporalEntry(UnqualifiedTemporalKey.create(key, timestamp), serializedNewValue); return entry; } // ================================================================================================================= // ABSTRACT METHOD DECLARATIONS // ================================================================================================================= /** * Returns the internally stored "now" timestamp. * * @return The internally stored "now" timestamp. Never negative. */ protected abstract long getNowInternal(); /** * Sets the "now" timestamp on this temporal key value store. * * @param timestamp The new timestamp to use as "now". Must not be negative. */ protected abstract void setNow(long timestamp); /** * Creates a new {@link TemporalDataMatrix} for the given keyspace. * * @param keyspace The name of the keyspace to create the matrix for. Must not be <code>null</code>. * @param timestamp The timestamp at which this keyspace was created. Must not be negative. * @return The newly created matrix instance for the given keyspace name. Never <code>null</code>. */ protected abstract TemporalDataMatrix createMatrix(String keyspace, long timestamp); /** * Stores the given {@link WriteAheadLogToken} in the persistent store. * * <p> * Non-persistent stores can safely ignore this method. * * @param token The token to store. Must not be <code>null</code>. */ protected abstract void performWriteAheadLog(WriteAheadLogToken token); /** * Clears the currently stored {@link WriteAheadLogToken} (if any). * * <p> * If no such token exists, this method does nothing. * * <p> * Non-persistent stores can safely ignore this method. */ protected abstract void clearWriteAheadLogToken(); /** * Attempts to return the currently stored {@link WriteAheadLogToken}. * * <p> * If no such token exists, this method returns <code>null</code>. * * <p> * Non-persistent stores can safely ignore this method and should always return <code>null</code>. * * @return The Write Ahead Log Token if it exists, otherwise <code>null</code>. */ protected abstract WriteAheadLogToken getWriteAheadLogTokenIfExists(); // ================================================================================================================= // INNER CLASSES // ================================================================================================================= private class AllEntriesIterator extends AbstractCloseableIterator<ChronoDBEntry> { private final long minTimestamp; private final long maxTimestamp; private Iterator<String> keyspaceIterator; private String currentKeyspace; private CloseableIterator<UnqualifiedTemporalEntry> currentEntryIterator; public AllEntriesIterator(final long minTimestamp, final long maxTimestamp) { AbstractTemporalKeyValueStore self = AbstractTemporalKeyValueStore.this; Set<String> keyspaces = Sets.newHashSet(self.getKeyspaces(maxTimestamp)); this.keyspaceIterator = keyspaces.iterator(); this.minTimestamp = minTimestamp; this.maxTimestamp = maxTimestamp; } private void tryMoveToNextIterator() { if (this.currentEntryIterator != null && this.currentEntryIterator.hasNext()) { // current iterator has more elements; stay here return; } // the current iterator is done, close it if (this.currentEntryIterator != null) { this.currentEntryIterator.close(); } while (true) { // move to the next keyspace (if possible) if (this.keyspaceIterator.hasNext() == false) { // we are at the end of all keyspaces this.currentKeyspace = null; this.currentEntryIterator = null; return; } // go to the next keyspace this.currentKeyspace = this.keyspaceIterator.next(); // acquire the entry iterator for this keyspace TemporalDataMatrix matrix = AbstractTemporalKeyValueStore.this.getMatrix(this.currentKeyspace); if (matrix == null) { // there is no entry for this keyspace in this store (may happen if we inherited keyspace from // parent branch) continue; } this.currentEntryIterator = matrix.allEntriesIterator(this.minTimestamp, this.maxTimestamp); if (this.currentEntryIterator.hasNext()) { // we found a non-empty iterator, stay here return; } else { // this iterator is empty as well; close it and move to the next iterator this.currentEntryIterator.close(); continue; } } } @Override protected boolean hasNextInternal() { this.tryMoveToNextIterator(); if (this.currentEntryIterator == null) { return false; } return this.currentEntryIterator.hasNext(); } @Override public ChronoDBEntry next() { if (this.hasNext() == false) { throw new NoSuchElementException(); } // fetch the next entry from our iterator UnqualifiedTemporalEntry rawEntry = this.currentEntryIterator.next(); // convert this entry into a full ChronoDBEntry Branch branch = AbstractTemporalKeyValueStore.this.getOwningBranch(); String keyspaceName = this.currentKeyspace; UnqualifiedTemporalKey unqualifiedKey = rawEntry.getKey(); String actualKey = unqualifiedKey.getKey(); byte[] actualValue = rawEntry.getValue(); long entryTimestamp = unqualifiedKey.getTimestamp(); ChronoIdentifier chronoIdentifier = ChronoIdentifier.create(branch, entryTimestamp, keyspaceName, actualKey); return ChronoDBEntry.create(chronoIdentifier, actualValue); } @Override protected void closeInternal() { if (this.currentEntryIterator != null) { this.currentEntryIterator.close(); this.currentEntryIterator = null; this.currentKeyspace = null; // "burn out" the keyspace iterator while (this.keyspaceIterator.hasNext()) { this.keyspaceIterator.next(); } } } } }
126,286
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AbstractDocumentBasedIndexManagerBackend.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/engines/base/AbstractDocumentBasedIndexManagerBackend.java
package org.chronos.chronodb.internal.impl.engines.base; import com.google.common.collect.HashMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.SetMultimap; import com.google.common.collect.Sets; import org.chronos.chronodb.api.Branch; import org.chronos.chronodb.api.Order; import org.chronos.chronodb.api.SecondaryIndex; import org.chronos.chronodb.api.TextCompare; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.internal.api.ChronoDBInternal; import org.chronos.chronodb.internal.api.index.ChronoIndexDocument; import org.chronos.chronodb.internal.api.index.ChronoIndexDocumentModifications; import org.chronos.chronodb.internal.api.index.DocumentBasedIndexManagerBackend; import org.chronos.chronodb.internal.api.query.searchspec.SearchSpecification; import org.chronos.chronodb.internal.impl.index.cursor.IndexScanCursor; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.*; public abstract class AbstractDocumentBasedIndexManagerBackend implements DocumentBasedIndexManagerBackend { // ================================================================================================================= // FIELDS // ================================================================================================================= protected final ChronoDBInternal owningDB; // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= protected AbstractDocumentBasedIndexManagerBackend(final ChronoDBInternal owningDB) { checkNotNull(owningDB, "Precondition violation - argument 'owningDB' must not be NULL!"); this.owningDB = owningDB; } // ===================================================================================================================== // PUBLIC API // ===================================================================================================================== @Override public Collection<ChronoIndexDocument> getMatchingDocuments(final long timestamp, final Branch branch, final String keyspace, final SearchSpecification<?, ?> searchSpec) { checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); checkNotNull(searchSpec, "Precondition violation - argument 'searchSpec' must not be NULL!"); List<SecondaryIndex> indices = this.owningDB.getIndexManager().getParentIndicesRecursive(searchSpec.getIndex(), true); Map<String, Branch> branchesByName = indices.stream() .map(idx -> this.owningDB.getBranchManager().getBranch(idx.getBranch())) .collect(Collectors.toMap(Branch::getName, Function.identity())); List<Branch> branches = Lists.reverse(indices.stream() .map(idx -> branchesByName.get(idx.getBranch())) .collect(Collectors.toList()) ); Map<Branch, SecondaryIndex> branchToIndex = indices.stream() .collect(Collectors.toMap(idx -> branchesByName.get(idx.getBranch()), Function.identity())); // we will later require information when a branch was "branched out" into the child branch we are interested // in, so we build this map now. It is a mapping from a branch to the timestamp when the relevant child branch // was created. It is the same info as branch#getBranchingTimestamp(), just attached to the parent (not the // child). // // Example: // We have: {"B", origin: "A", timestamp: 1234}, {"A", origin: "master", timestamp: 123}, {"master"} // We need: {"master" branchedIntoA_At: 123} {"A" branchedIntoB_At: 1234} {"B"} Map<Branch, Long> branchOutTimestamps = Maps.newHashMap(); for (int i = 0; i < branches.size(); i++) { Branch b = branches.get(i); if (b.equals(branch)) { // the request branch has no "branch out" timestamp continue; } Branch childBranch = branches.get(i + 1); // the root branch was "branched out" to the child branch at this timestamp branchOutTimestamps.put(b, childBranch.getBranchingTimestamp()); } // prepare a mapping from qualified keys to document that holds our result SetMultimap<QualifiedKey, ChronoIndexDocument> resultMap = HashMultimap.create(); // now, iterate over the list and repeat the matching algorithm for every branch: // 1) Collect the matches from the origin branch // 2) Remove from these matches all of those which were deleted in our current branch // 3) Add the matches local to our current branch for (Branch currentBranch : branches) { SearchSpecification<?, ?> branchSearchSpec; if (branch.equals(currentBranch)) { branchSearchSpec = searchSpec; } else { SecondaryIndex branchLocalIndex = branchToIndex.get(currentBranch); branchSearchSpec = searchSpec.onIndex(branchLocalIndex); } String branchName = currentBranch.getName(); // Important note: if the branch we are currently dealing with is NOT the branch that we are // querying, but a PARENT branch instead, we must use the MINIMUM of (branching timestamp; request // timestamp), because the branch might have changes that are AFTER the branching timestamp but BEFORE the // request timestamp, and we don't want to see those in the result. long scanTimestamp = timestamp; if (currentBranch.equals(branch) == false) { // not the request timestamp; calculate the scan timestamp long branchOutTimestamp = branchOutTimestamps.get(currentBranch); scanTimestamp = Math.min(timestamp, branchOutTimestamp); } // check if we have a non-empty result set (in that case, we have to respect branch-local deletions) if (resultMap.isEmpty() == false) { // find the branch-local deletions Collection<ChronoIndexDocument> localDeletions = this.getTerminatedBranchLocalDocuments(scanTimestamp, branchName, keyspace, branchSearchSpec); // remove the local deletions from our overall result for (ChronoIndexDocument localDeletion : localDeletions) { QualifiedKey qKey = QualifiedKey.create(localDeletion.getKeyspace(), localDeletion.getKey()); Set<ChronoIndexDocument> docsToCheck = Sets.newHashSet(resultMap.get(qKey)); // remove all those documents which name the same value as the local deletion for (ChronoIndexDocument document : docsToCheck) { if (document.getIndexedValue().equals(localDeletion.getIndexedValue())) { // this document was deleted in the current branch, remove it from the overall result resultMap.remove(qKey, document); } } } } // find the branch-local matches of the given branch. Collection<ChronoIndexDocument> localMatches = this.getMatchingBranchLocalDocuments(scanTimestamp, branchName, keyspace, branchSearchSpec); // add the local matches to our overall result for (ChronoIndexDocument localMatch : localMatches) { QualifiedKey qKey = QualifiedKey.create(localMatch.getKeyspace(), localMatch.getKey()); resultMap.put(qKey, localMatch); } } // finally, we are only interested in the values from the result map, as they form our query result. return Collections.unmodifiableSet(Sets.newHashSet(resultMap.values())); } public void rollback(final Set<SecondaryIndex> indices, final long timestamp) { checkNotNull(indices, "Precondition violation - argument 'branches' must not be NULL!"); checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); // "null" in the second argument means "roll back all keys" this.rollbackInternal(timestamp, indices, null); } public void rollback(final Set<SecondaryIndex> indices, final long timestamp, final Set<QualifiedKey> keys) { checkNotNull(indices, "Precondition violation - argument 'indices' must not be NULL!"); checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); checkNotNull(keys, "Precondition violation - argument 'keys' must not be NULL!"); this.rollbackInternal(timestamp, indices, keys); } // ===================================================================================================================== // INTERNAL HELPER METHODS // ===================================================================================================================== /** * Performs the actual rollback operation on this index. * * @param timestamp The timestamp to roll back to. Must not be negative. * @param keys The set of keys to roll back. If the set is <code>null</code>, <b>all</b> keys will be rolled back. If the set is empty, no keys will be rolled back. If the set is non-empty, only the given keys will be rolled back. */ protected void rollbackInternal(final long timestamp, final Set<SecondaryIndex> indices, final Set<QualifiedKey> keys) { if (keys != null && keys.isEmpty()) { // we have no keys to roll back; method is a no-op. return; } // get the set of all documents that were added and/or modified at or after the given timestamp Set<ChronoIndexDocument> documents = this.getDocumentsTouchedAtOrAfterTimestamp(timestamp, indices); // prepare the index modification set ChronoIndexDocumentModifications indexModifications = ChronoIndexDocumentModifications.create(); for (ChronoIndexDocument document : documents) { // check if we need to process this document (i.e. if it is relevant for the rollback) if (indices.contains(document.getIndex()) == false) { // document does not belong to a relevant branch; skip it continue; } if (this.isDocumentRelevantForRollback(document, keys) == false) { continue; } // document is relevant, perform the rollback long validFrom = document.getValidFromTimestamp(); long validTo = document.getValidToTimestamp(); // check if the document was created strictly after our timestamp if (validFrom > timestamp) { // delete this document indexModifications.addDocumentDeletion(document); } else { // check if the document validity has been trimmed to a value after our timestamp if (validTo < Long.MAX_VALUE && validTo >= timestamp) { // reset the document validity to infinity indexModifications.addDocumentValidityTermination(document, Long.MAX_VALUE); } } } if (indexModifications.isEmpty() == false) { // perform the deletions this.applyModifications(indexModifications); } } /** * A helper method to determine if the given document is relevant for rollback with respect to the set of keys to roll back. * * @param document The document to check. Must not be <code>null</code>. * @param keys The set of keys to roll back. May be <code>null</code> to indicate that all keys will be rolled back. * @return If the given set is <code>null</code>, this method will always return <code>true</code>. If the set is empty, this method will always return <code>false</code>. Otherwise, this method returns <code>true</code> if and only if the document is bound to a qualified key that is in this set. */ protected boolean isDocumentRelevantForRollback(final ChronoIndexDocument document, final Set<QualifiedKey> keys) { if (keys == null) { // use all documents return true; } if (keys.isEmpty()) { // use no documents return false; } // check if the document is bound to one of the keys we should roll back String keyspace = document.getKeyspace(); String key = document.getKey(); QualifiedKey qKey = QualifiedKey.create(keyspace, key); if (keys.contains(qKey) == false) { return false; } else { return true; } } // ===================================================================================================================== // ABSTRACT METHOD DECLARATIONS // ===================================================================================================================== /** * Returns the set of documents that were added and/or modified exactly at the given timestamp, or after the given timestamp. * * @param timestamp The timestamp in question. Must not be negative. * @param indices The set of indices to retrieve the documents for. If <code>null</code>, documents from all branches will be retrieved. If this set is empty, then the result set will also be empty. * @return The set of index documents that were added and/or modified exactly at or after the given timestamp. May be empty, but never <code>null</code>. */ protected abstract Set<ChronoIndexDocument> getDocumentsTouchedAtOrAfterTimestamp(long timestamp, Set<SecondaryIndex> indices); protected abstract Collection<ChronoIndexDocument> getTerminatedBranchLocalDocuments(long timestamp, String branchName, String keyspace, SearchSpecification<?, ?> searchSpec); protected abstract Collection<ChronoIndexDocument> getMatchingBranchLocalDocuments(long timestamp, String branchName, String keyspace, SearchSpecification<?, ?> searchSpec); public abstract 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 ); }
15,360
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
KeyspaceMetadata.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/engines/base/KeyspaceMetadata.java
package org.chronos.chronodb.internal.impl.engines.base; import static com.google.common.base.Preconditions.*; import java.io.Serializable; public class KeyspaceMetadata implements Serializable { private String keyspaceName; private String matrixTableName; private long creationTimestamp; protected KeyspaceMetadata() { // default constructor for serialization } public KeyspaceMetadata(final String keyspaceName, final String matrixTableName, final long creationTimestamp) { checkNotNull(keyspaceName, "Precondition violation - argument 'keyspaceName' must not be NULL!"); checkNotNull(matrixTableName, "Precondition violation - argument 'matrixTableName' must not be NULL!"); checkArgument(creationTimestamp >= 0, "Precondition violation - argument 'creationTimestamp' must not be negative!"); this.keyspaceName = keyspaceName; this.matrixTableName = matrixTableName; this.creationTimestamp = creationTimestamp; } public String getKeyspaceName() { return this.keyspaceName; } public String getMatrixTableName() { return this.matrixTableName; } public long getCreationTimestamp() { return this.creationTimestamp; } }
1,161
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronosInternalCommitMetadata.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/engines/base/ChronosInternalCommitMetadata.java
package org.chronos.chronodb.internal.impl.engines.base; import static com.google.common.base.Preconditions.*; public class ChronosInternalCommitMetadata { private Object payload; protected ChronosInternalCommitMetadata(){ // default constructor for (de-)serialization } public ChronosInternalCommitMetadata(Object payload){ checkNotNull(payload, "Precondition violation - argument 'payload' must not be NULL!"); this.payload = payload; } public Object getPayload() { return payload; } @Override public String toString() { return "ChronosInternalCommitMetadata[" + this.payload + "]"; } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ChronosInternalCommitMetadata that = (ChronosInternalCommitMetadata) o; return payload != null ? payload.equals(that.payload) : that.payload == null; } @Override public int hashCode() { return payload != null ? payload.hashCode() : 0; } }
1,142
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AbstractStatisticsManager.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/engines/base/AbstractStatisticsManager.java
package org.chronos.chronodb.internal.impl.engines.base; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.collect.Lists; import org.chronos.chronodb.api.BranchHeadStatistics; import org.chronos.chronodb.api.ChronoDBStatistics; import org.chronos.chronodb.api.exceptions.ChronoDBException; import org.chronos.chronodb.api.exceptions.ChronoDBStorageBackendException; import org.chronos.chronodb.internal.api.StatisticsManagerInternal; import org.chronos.chronodb.internal.impl.BranchHeadStatisticsImpl; import java.io.IOException; import java.util.List; import java.util.Optional; import java.util.concurrent.ExecutionException; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public abstract class AbstractStatisticsManager implements StatisticsManagerInternal { // ================================================================================================================= // FIELDS // ================================================================================================================= private final ReadWriteLock statisticsLock = new ReentrantReadWriteLock(true); private final LoadingCache<String, BranchHeadStatistics> branchToHeadStatistics; // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= public AbstractStatisticsManager() { this.branchToHeadStatistics = CacheBuilder.newBuilder().build(new CacheLoader<String, BranchHeadStatistics>() { @Override public BranchHeadStatistics load(final String key) throws Exception { return AbstractStatisticsManager.this.loadBranchHeadStatistics(key); } }); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public ChronoDBStatistics getGlobalStatistics() { throw new UnsupportedOperationException("Not implemented yet!"); } @Override public BranchHeadStatistics getBranchHeadStatistics(final String branchName) { this.statisticsLock.readLock().lock(); try { return this.branchToHeadStatistics.get(branchName); } catch (ExecutionException e) { throw new ChronoDBException("Failed to calculate head statistics!", e); } finally { this.statisticsLock.readLock().unlock(); } } // ================================================================================================================= // INTERNAL API // ================================================================================================================= @Override public void updateBranchHeadStatistics(String branchName, long inserts, long updates, long deletes) { this.statisticsLock.writeLock().lock(); try { Optional<BranchHeadStatistics> maybeHeadStats = Optional.ofNullable(this.branchToHeadStatistics.getIfPresent(branchName)); if(maybeHeadStats.isPresent()){ BranchHeadStatistics oldStatistics = maybeHeadStats.get(); long numberOfEntriesInHead = oldStatistics.getNumberOfEntriesInHead(); long totalNumberOfEntries = oldStatistics.getTotalNumberOfEntries(); //changes entries in head numberOfEntriesInHead += inserts; numberOfEntriesInHead -= deletes; //changes total entries totalNumberOfEntries += inserts; totalNumberOfEntries += deletes; totalNumberOfEntries += updates; BranchHeadStatistics newStatistics = new BranchHeadStatisticsImpl(numberOfEntriesInHead, totalNumberOfEntries); this.branchToHeadStatistics.put(branchName, newStatistics); this.saveBranchHeadStatistics(branchName, newStatistics); }else{ // calculate from scratch BranchHeadStatistics newStatistics = this.loadBranchHeadStatistics(branchName); this.branchToHeadStatistics.put(branchName, newStatistics); this.saveBranchHeadStatistics(branchName, newStatistics); } } finally { this.statisticsLock.writeLock().unlock(); } } @Override public void clearBranchHeadStatistics() { this.statisticsLock.writeLock().lock(); try{ this.branchToHeadStatistics.invalidateAll(); this.deleteBranchHeadStatistics(); }finally{ this.statisticsLock.writeLock().unlock(); } } @Override public void clearBranchHeadStatistics(final String branchName) { this.statisticsLock.writeLock().lock(); try{ this.branchToHeadStatistics.invalidate(branchName); this.deleteBranchHeadStatistics(branchName); }finally{ this.statisticsLock.writeLock().unlock(); } } // ================================================================================================================= // ABSTRACT METHODS // ================================================================================================================= protected abstract BranchHeadStatistics loadBranchHeadStatistics(String branch); protected abstract void saveBranchHeadStatistics(String branchName, BranchHeadStatistics statistics); protected abstract void deleteBranchHeadStatistics(); protected abstract void deleteBranchHeadStatistics(String branchName); }
6,011
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
WriteAheadLogToken.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/engines/base/WriteAheadLogToken.java
package org.chronos.chronodb.internal.impl.engines.base; import static com.google.common.base.Preconditions.*; public class WriteAheadLogToken { private long nowTimestampBeforeCommit; private long nowTimestampAfterCommit; protected WriteAheadLogToken() { // no-args for serialization } public WriteAheadLogToken(final long nowTimestampBeforeCommit, final long nowTimestampAfterCommit) { checkArgument(nowTimestampBeforeCommit >= 0, "Precondition violation - argument 'nowTimestampBeforeCommit' must not be negative!"); checkArgument(nowTimestampAfterCommit >= 0, "Precondition violation - argument 'nowTimestampAfterCommit' must not be negative!"); checkArgument(nowTimestampAfterCommit > nowTimestampBeforeCommit, "Precondition violation - argument 'nowTimestampAfterCommit' must be strictly greater than 'nowTimestampBeforeCommit'!"); this.nowTimestampBeforeCommit = nowTimestampBeforeCommit; this.nowTimestampAfterCommit = nowTimestampAfterCommit; } public long getNowTimestampBeforeCommit() { return this.nowTimestampBeforeCommit; } public long getNowTimestampAfterCommit() { return this.nowTimestampAfterCommit; } }
1,154
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
StandardChronoDBTransaction.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/engines/base/StandardChronoDBTransaction.java
package org.chronos.chronodb.internal.impl.engines.base; import com.google.common.collect.Maps; import org.chronos.chronodb.api.*; import org.chronos.chronodb.api.builder.query.QueryBuilderFinalizer; import org.chronos.chronodb.api.builder.query.QueryBuilderStarter; import org.chronos.chronodb.api.exceptions.ChronoDBCommitException; import org.chronos.chronodb.api.exceptions.TransactionIsReadOnlyException; import org.chronos.chronodb.api.exceptions.UnknownKeyspaceException; import org.chronos.chronodb.api.exceptions.ValueTypeMismatchException; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.api.key.TemporalKey; import org.chronos.chronodb.internal.api.TemporalKeyValueStore; import org.chronos.chronodb.internal.api.query.ChronoDBQuery; import java.util.*; import java.util.Map.Entry; import static com.google.common.base.Preconditions.*; public class StandardChronoDBTransaction implements ChronoDBTransaction { protected long timestamp; protected final TemporalKeyValueStore tkvs; protected final String branchIdentifier; protected final Map<QualifiedKey, ChangeSetEntry> changeSet = Maps.newHashMap(); protected final Configuration configuration; protected boolean incrementalCommitProcessActive = false; protected long incrementalCommitProcessTimestamp = -1L; public StandardChronoDBTransaction(final TemporalKeyValueStore tkvs, final long timestamp, final String branchIdentifier, final Configuration configuration) { checkNotNull(tkvs, "Precondition violation - argument 'tkvs' must not be NULL!"); checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative (value: " + timestamp + ")!"); checkNotNull(branchIdentifier, "Precondition violation - argument 'branchIdentifier' must not be NULL!"); checkNotNull(configuration, "Precondition violation - argument 'configuration' must not be NULL!"); this.tkvs = tkvs; this.timestamp = timestamp; this.branchIdentifier = branchIdentifier; this.configuration = configuration; } @Override public long getTimestamp() { if (this.incrementalCommitProcessActive) { if (this.incrementalCommitProcessTimestamp < 0) { // incremental commit process first commit is active; use the normal timestamp for now return this.timestamp; } else { return this.incrementalCommitProcessTimestamp; } } else { return this.timestamp; } } @Override public String getBranchName() { return this.branchIdentifier; } // ================================================================================================================= // OPERATION [ GET ] // ================================================================================================================= @Override public <T> T get(final String key) throws ValueTypeMismatchException { checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); QualifiedKey qKey = QualifiedKey.createInDefaultKeyspace(key); return this.getInternal(qKey); } @Override public byte[] getBinary(final String key) throws UnknownKeyspaceException { checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); return this.getInternalBinary(QualifiedKey.createInDefaultKeyspace(key)); } @Override public <T> T get(final String keyspaceName, final String key) throws ValueTypeMismatchException, UnknownKeyspaceException { checkNotNull(keyspaceName, "Precondition violation - argument 'keyspaceName' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); QualifiedKey qKey = QualifiedKey.create(keyspaceName, key); return this.getInternal(qKey); } @Override public byte[] getBinary(final String keyspaceName, final String key) throws UnknownKeyspaceException { checkNotNull(keyspaceName, "Precondition violation - argument 'keyspaceName' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); return this.getInternalBinary(QualifiedKey.create(keyspaceName, key)); } protected <T> T getInternal(final QualifiedKey key) throws ValueTypeMismatchException, UnknownKeyspaceException { Object value = this.getTKVS().performGet(this, key); if (value == null) { return null; } try { return (T) value; } catch (ClassCastException e) { throw new ValueTypeMismatchException( "Value of key '" + key + "' is of unexpected class '" + value.getClass().getName() + "'!", e); } } protected byte[] getInternalBinary(final QualifiedKey key) throws UnknownKeyspaceException { return this.getTKVS().performGetBinary(this, key); } // ================================================================================================================= // OPERATION [ EXISTS ] // ================================================================================================================= @Override public boolean exists(final String key) { checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); QualifiedKey qKey = QualifiedKey.createInDefaultKeyspace(key); return this.existsInternal(qKey); } @Override public boolean exists(final String keyspaceName, final String key) { checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); QualifiedKey qKey = QualifiedKey.create(keyspaceName, key); return this.existsInternal(qKey); } protected boolean existsInternal(final QualifiedKey key) { // TODO PERFORMANCE JDBC: implement 'exists' natively instead of 'get' (network overhead due to blob transfer) Object value = this.getTKVS().performGet(this, key); return value != null; } // ================================================================================================================= // OPERATION [ KEY SET ] // ================================================================================================================= @Override public Set<String> keySet() { return this.keySetInternal(ChronoDBConstants.DEFAULT_KEYSPACE_NAME); } @Override public Set<String> keySet(final String keyspaceName) { checkNotNull(keyspaceName, "Precondition violation - argument 'keyspaceName' must not be NULL!"); return this.keySetInternal(keyspaceName); } protected Set<String> keySetInternal(final String keyspaceName) { return this.getTKVS().performKeySet(this, keyspaceName); } // ================================================================================================================= // OPERATION [ HISTORY ] // ================================================================================================================= @Override public Iterator<Long> history(final String keyspaceName, final String key, final long lowerBound, final long upperBound, final Order order) { checkNotNull(keyspaceName, "Precondition violation - argument 'keyspaceName' must not be NULL!"); 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(upperBound >= lowerBound, "Precondition violation - argument 'upperBound' must be greater than or equal to argument 'lowerBound'!"); checkArgument(lowerBound <= this.getTimestamp(), "Precondition violation - argument 'lowerBound' must be less than or equal to the transaction timestamp!"); checkArgument(upperBound <= this.getTimestamp(), "Precondition violation - argument 'upperBound' must be less than or equal to the transaction timestamp!"); checkNotNull(order, "Precondition violation - argument 'order' must not be NULL!"); QualifiedKey qKey = QualifiedKey.create(keyspaceName, key); return this.getTKVS().performHistory(this, qKey, lowerBound, upperBound, order); } @Override public long getLastModificationTimestamp(final String keyspace, final String key) { checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); QualifiedKey qKey = QualifiedKey.create(keyspace, key); return this.getTKVS().performGetLastModificationTimestamp(this, qKey); } // ================================================================================================================= // OPERATION [ MODIFICATIONS BETWEEN ] // ================================================================================================================= @Override public Iterator<TemporalKey> getModificationsInKeyspaceBetween(final String keyspace, final long timestampLowerBound, final long timestampUpperBound) { checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkArgument(timestampLowerBound >= 0, "Precondition violation - argument 'timestampLowerBound' must not be negative!"); checkArgument(timestampUpperBound >= 0, "Precondition violation - argument 'timestampUpperBound' must not be negative!"); checkArgument(timestampLowerBound <= this.getTimestamp(), "Precondition violation - argument 'timestampLowerBound' must not exceed the transaction timestamp!"); checkArgument(timestampUpperBound <= this.getTimestamp(), "Precondition violation - argument 'timestampUpperBound' must not exceed the transaction timestamp!"); checkArgument(timestampLowerBound <= timestampUpperBound, "Precondition violation - argument 'timestampLowerBound' must be less than or equal to 'timestampUpperBound'!"); return this.getTKVS().performGetModificationsInKeyspaceBetween(this, keyspace, timestampLowerBound, timestampUpperBound); } // ===================================================================================================================== // COMMIT METADATA STORE OPERATIONS // ===================================================================================================================== @Override public Iterator<Long> getCommitTimestampsBetween(final long from, final long to, final Order order, final boolean includeSystemInternalCommits) { checkArgument(from >= 0, "Precondition violation - argument 'from' must not be negative!"); checkArgument(from <= this.getTimestamp(), "Precondition violation - argument 'from' must not be larger than the transaction timestamp!"); checkArgument(to >= 0, "Precondition violation - argument 'to' must not be negative!"); checkArgument(to <= this.getTimestamp(), "Precondition violation - argument 'to' must not be larger than the transaction timestamp!"); checkNotNull(order, "Precondition violation - argument 'order' must not be NULL!"); return this.getTKVS().performGetCommitTimestampsBetween(this, from, to, order, includeSystemInternalCommits); } @Override public Iterator<Entry<Long, Object>> getCommitMetadataBetween(final long from, final long to, final Order order, final boolean includeSystemInternalCommits) { checkArgument(from >= 0, "Precondition violation - argument 'from' must not be negative!"); checkArgument(from <= this.getTimestamp(), "Precondition violation - argument 'from' must not be larger than the transaction timestamp!"); checkArgument(to >= 0, "Precondition violation - argument 'to' must not be negative!"); checkArgument(to <= this.getTimestamp(), "Precondition violation - argument 'to' must not be larger than the transaction timestamp!"); checkNotNull(order, "Precondition violation - argument 'order' must not be NULL!"); return this.getTKVS().performGetCommitMetadataBetween(this, from, to, order, includeSystemInternalCommits); } @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(minTimestamp <= this.getTimestamp(), "Precondition violation - argument 'minTimestamp' must not be larger than the transaction timestamp!"); checkArgument(maxTimestamp >= 0, "Precondition violation - argument 'maxTimestamp' must not be negative!"); checkArgument(maxTimestamp <= this.getTimestamp(), "Precondition violation - argument 'maxTimestamp' must not be larger than the transaction timestamp!"); 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!"); return this.getTKVS().performGetCommitTimestampsPaged(this, minTimestamp, maxTimestamp, pageSize, pageIndex, order, includeSystemInternalCommits); } @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(minTimestamp <= this.getTimestamp(), "Precondition violation - argument 'minTimestamp' must not be larger than the transaction timestamp!"); checkArgument(maxTimestamp >= 0, "Precondition violation - argument 'maxTimestamp' must not be negative!"); checkArgument(maxTimestamp <= this.getTimestamp(), "Precondition violation - argument 'maxTimestamp' must not be larger than the transaction timestamp!"); 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!"); return this.getTKVS().performGetCommitMetadataPaged(this, minTimestamp, maxTimestamp, pageSize, pageIndex, order, includeSystemInternalCommits); } @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!"); return this.getTKVS().performGetCommitMetadataAround(timestamp, count, includeSystemInternalCommits); } @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!"); return this.getTKVS().performGetCommitMetadataBefore(timestamp, count, includeSytemInternalCommits); } @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!"); return this.getTKVS().performGetCommitMetadataAfter(timestamp, count, includeSystemInternalCommits); } @Override public List<Long> getCommitTimestampsAround(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!"); return this.getTKVS().performGetCommitTimestampsAround(timestamp, count, includeSystemInternalCommits); } @Override public List<Long> getCommitTimestampsBefore(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!"); return this.getTKVS().performGetCommitTimestampsBefore(timestamp, count, includeSystemInternalCommits); } @Override public List<Long> getCommitTimestampsAfter(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!"); return this.getTKVS().performGetCommitTimestampsAfter(timestamp, count, includeSystemInternalCommits); } @Override public int countCommitTimestampsBetween(final long from, final long to, final boolean includeSystemIternalCommits) { checkArgument(from >= 0, "Precondition violation - argument 'from' must not be negative!"); checkArgument(from <= this.getTimestamp(), "Precondition violation - argument 'from' must not be larger than the transaction timestamp!"); checkArgument(to >= 0, "Precondition violation - argument 'to' must not be negative!"); checkArgument(to <= this.getTimestamp(), "Precondition violation - argument 'to' must not be larger than the transaction timestamp!"); return this.getTKVS().performCountCommitTimestampsBetween(this, from, to, includeSystemIternalCommits); } @Override public int countCommitTimestamps(final boolean includeSystemInternalCommits) { return this.getTKVS().performCountCommitTimestamps(this, includeSystemInternalCommits); } // ===================================================================================================================== // OPERATION [ GET COMMIT METADATA ] // ===================================================================================================================== @Override public Object getCommitMetadata(final long commitTimestamp) { checkArgument(commitTimestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); checkArgument(commitTimestamp <= this.getTimestamp(), "Precondition violation - argument 'timestamp' must not be greater than the transaction timestamp!"); return this.getTKVS().performGetCommitMetadata(this, commitTimestamp); } // ================================================================================================================= // OPERATION [ GET CHANGED KEYS AT COMMIT] // ================================================================================================================= @Override public Iterator<String> getChangedKeysAtCommit(final long timestamp) { return this.getChangedKeysAtCommit(timestamp, ChronoDBConstants.DEFAULT_KEYSPACE_NAME); } @Override public Iterator<String> getChangedKeysAtCommit(final long commitTimestamp, final String keyspace) { checkArgument(commitTimestamp >= 0, "Precondition violation - argument 'commitTimestamp' must not be negative!"); checkArgument(commitTimestamp <= this.getTimestamp(), "Precondition violation - argument 'commitTimestamp' must not be larger than the transaction timestamp!"); checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); return this.getTKVS().performGetChangedKeysAtCommit(this, commitTimestamp, keyspace); } // ================================================================================================================= // OPERATION [ KEYSPACES ] // ================================================================================================================= @Override public Set<String> keyspaces() { return this.getTKVS().getKeyspaces(this); } // ================================================================================================================= // QUERY METHODS // ================================================================================================================= @Override public QueryBuilderStarter find() { return this.tkvs.getOwningDB().getQueryManager().createQueryBuilder(this); } @Override public QueryBuilderFinalizer find(final ChronoDBQuery query) { return this.tkvs.getOwningDB().getQueryManager().createQueryBuilderFinalizer(this, query); } // ================================================================================================================= // TRANSACTION CONTROL // ================================================================================================================= @Override public long commit() throws ChronoDBCommitException { return this.commit(null); } @Override public long commit(final Object commitMetadata) throws ChronoDBCommitException { if (this.getConfiguration().isReadOnly()) { throw new ChronoDBCommitException("Cannot perform a commit; this database instance is read-only!"); } try { long time = this.getTKVS().performCommit(this, commitMetadata); this.changeSet.clear(); this.timestamp = this.getTKVS().getNow(); return time; } finally { // a commit ALWAYS aborts incremental commit mode, regardless of // whether it succeeds or not this.incrementalCommitProcessActive = false; this.incrementalCommitProcessTimestamp = -1L; } } @Override public void commitIncremental() throws ChronoDBCommitException { if (this.getConfiguration().isReadOnly()) { throw new ChronoDBCommitException("Cannot perform a commit; this database instance is read-only!"); } try { this.incrementalCommitProcessActive = true; long newTimestamp = this.getTKVS().performCommitIncremental(this); this.changeSet.clear(); this.incrementalCommitProcessTimestamp = newTimestamp; } catch (ChronoDBCommitException e) { // abort the incremental commit. this.incrementalCommitProcessTimestamp = -1L; this.incrementalCommitProcessActive = false; // clear the change set this.changeSet.clear(); // propagete the exception throw new ChronoDBCommitException("Error during incremental commit. " + "Commit process was canceled, any modifications were rolled back. " + "See root cause for details.", e); } } @Override public boolean isInIncrementalCommitMode() { return this.incrementalCommitProcessActive; } @Override public void rollback() { if (this.incrementalCommitProcessActive) { // abort the incremental commit process and perform the rollback on the underlying TKVS this.getTKVS().performIncrementalRollback(this); this.incrementalCommitProcessActive = false; this.incrementalCommitProcessTimestamp = -1L; this.changeSet.clear(); } else { // this operation is simple: as the change set is held in-memory, the entire "state" of this object // IS the change set. By clearing the change set, we reset the entire transaction. this.changeSet.clear(); } } // ================================================================================================================= // OPERATION [ PUT ] // ================================================================================================================= @Override public void put(final String key, final Object value) { checkNotNull(value, "Argument 'value' must not be NULL! Use 'remove(...)' instead to remove it from the store."); this.put(key, value, PutOption.NONE); } @Override public void put(final String key, final Object value, final PutOption... options) { this.assertIsReadWrite(); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); checkNotNull(value, "Argument 'value' must not be NULL! Use 'remove(...)' instead to remove it from the store."); checkNotNull(options, "Precondition violation - argument 'options' must not be NULL!"); QualifiedKey qKey = QualifiedKey.createInDefaultKeyspace(key); this.putInternal(qKey, value, options); } @Override public void put(final String keyspaceName, final String key, final Object value) { this.put(keyspaceName, key, value, PutOption.NONE); } @Override public void put(final String keyspaceName, final String key, final Object value, final PutOption... options) { this.assertIsReadWrite(); checkNotNull(keyspaceName, "Precondition violation - argument 'keyspaceName' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); checkNotNull(value, "Precondition violation - argument 'value' must not be NULL!"); checkNotNull(options, "Precondition violation - argument 'options' must not be NULL!"); QualifiedKey qKey = QualifiedKey.create(keyspaceName, key); this.putInternal(qKey, value, options); } protected void putInternal(final QualifiedKey key, final Object value, final PutOption[] options) { ChangeSetEntry entry = ChangeSetEntry.createChange(key, value, options); this.changeSet.put(key, entry); } // ================================================================================================================= // OPERATION [ REMOVE ] // ================================================================================================================= @Override public void remove(final String key) { this.assertIsReadWrite(); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); QualifiedKey qKey = QualifiedKey.createInDefaultKeyspace(key); this.removeInternal(qKey); } @Override public void remove(final String keyspaceName, final String key) { this.assertIsReadWrite(); checkNotNull(keyspaceName, "Precondition violation - argument 'keyspaceName' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); QualifiedKey qKey = QualifiedKey.create(keyspaceName, key); this.removeInternal(qKey); } protected void removeInternal(final QualifiedKey key) { ChangeSetEntry entry = ChangeSetEntry.createDeletion(key); this.changeSet.put(key, entry); } // ================================================================================================================= // MISCELLANEOUS API METHODS // ================================================================================================================= @Override public Collection<ChangeSetEntry> getChangeSet() { return Collections.unmodifiableCollection(this.changeSet.values()); } @Override public Configuration getConfiguration() { return this.configuration; } /** * Clears this transaction and resets the timestamp to HEAD. * <p> * The branch on which this transaction operates remains unchanged. * All uncommitted changes will be lost. * This operation is not supported while in incremental commit mode. * </p> * <b><u>/!\ WARNING /!\</u></b> * This method is for internal use only! */ public void cancelAndResetToHead() { if (this.incrementalCommitProcessActive) { throw new IllegalStateException("Resetting to HEAD is not supported in incremental commit mode!"); } this.changeSet.clear(); this.timestamp = this.getTKVS().getNow(); } // ================================================================================================================= // INTERNAL HELPER METHODS // ================================================================================================================= protected TemporalKeyValueStore getTKVS() { return this.tkvs; } protected void assertIsReadWrite() { if (this.getConfiguration().isReadOnly()) { throw new TransactionIsReadOnlyException( "This transaction is read-only. Cannot perform modification operation."); } } }
30,334
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChangeSet.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/engines/base/ChangeSet.java
package org.chronos.chronodb.internal.impl.engines.base; import static com.google.common.base.Preconditions.*; import java.util.Collections; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import org.apache.commons.lang3.tuple.Pair; import org.chronos.chronodb.api.key.ChronoIdentifier; import org.chronos.chronodb.api.key.QualifiedKey; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; public class ChangeSet { private final Map<String, Map<String, Object>> keyspaceToKeyToValue = Maps.newHashMap(); private final Map<ChronoIdentifier, Pair<Object, Object>> entriesToIndex = Maps.newHashMap(); public void addEntry(final String keyspace, final String key, final Object value) { checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); Map<String, Object> keyspaceMap = this.keyspaceToKeyToValue.get(keyspace); if (keyspaceMap == null) { keyspaceMap = Maps.newHashMap(); this.keyspaceToKeyToValue.put(keyspace, keyspaceMap); } keyspaceMap.put(key, value); } public void addEntryToIndex(final ChronoIdentifier identifier, final Object oldValue, final Object newValue) { checkNotNull(identifier, "Precondition violation - argument 'identifier' must not be NULL!"); this.entriesToIndex.put(identifier, Pair.of(oldValue, newValue)); } public Iterable<Entry<String, Map<String, byte[]>>> getSerializedEntriesByKeyspace( final Function<Object, byte[]> serializer) { Set<Entry<String, Map<String, Object>>> set = this.keyspaceToKeyToValue.entrySet(); return Iterables.transform(set, entry -> { String keyspace = entry.getKey(); Map<String, Object> contents = entry.getValue(); Map<String, byte[]> serialContents = Maps.transformValues(contents, value -> { if (value == null) { return null; } else { return serializer.apply(value); } }); return Pair.of(keyspace, serialContents); }); } public Set<QualifiedKey> getModifiedKeys() { return this.entriesToIndex.keySet().stream().map(id -> QualifiedKey.create(id.getKeyspace(), id.getKey())) .collect(Collectors.toSet()); } public Map<ChronoIdentifier, Pair<Object, Object>> getEntriesToIndex() { return Collections.unmodifiableMap(this.entriesToIndex); } public Map<String, Map<String, Object>> getEntriesByKeyspace() { return Collections.unmodifiableMap(this.keyspaceToKeyToValue); } public Set<String> getModifiedKeyspaces() { return Collections.unmodifiableSet(this.keyspaceToKeyToValue.keySet()); } public int size() { return this.keyspaceToKeyToValue.values().stream().mapToInt(Map::size).sum(); } }
2,800
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
BranchDirectoryNameResolver.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/engines/base/BranchDirectoryNameResolver.java
package org.chronos.chronodb.internal.impl.engines.base; @FunctionalInterface public interface BranchDirectoryNameResolver { public String createDirectoryNameForBranchName(String branchName); public static final BranchDirectoryNameResolver NULL_NAME_RESOLVER = branchName -> null; }
294
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AbstractBranchManager.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/engines/base/AbstractBranchManager.java
package org.chronos.chronodb.internal.impl.engines.base; import com.google.common.collect.ListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Multimaps; import com.google.common.collect.Sets; import org.chronos.chronodb.api.Branch; import org.chronos.chronodb.api.BranchManager; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.exceptions.ChronoDBBranchingException; import org.chronos.chronodb.internal.api.BranchEventListener; import org.chronos.chronodb.internal.api.BranchInternal; import org.chronos.chronodb.internal.api.BranchManagerInternal; import org.chronos.chronodb.internal.api.ChronoDBInternal; import org.chronos.chronodb.internal.impl.IBranchMetadata; import org.chronos.common.autolock.AutoLock; import org.jetbrains.annotations.NotNull; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Queue; import java.util.Set; import java.util.concurrent.LinkedBlockingQueue; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.*; public abstract class AbstractBranchManager implements BranchManager, BranchManagerInternal { // ================================================================================================================= // FIELDS // ================================================================================================================= protected final BranchDirectoryNameResolver dirNameResolver; protected final Set<BranchEventListener> eventListeners = Sets.newHashSet(); // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= protected AbstractBranchManager(final BranchDirectoryNameResolver branchDirectoryNameResolver) { checkNotNull(branchDirectoryNameResolver, "Precondition violation - argument 'branchDirectoryNameResolver' must not be NULL!"); this.dirNameResolver = branchDirectoryNameResolver; } // ===================================================================================================================== // PUBLIC API // ===================================================================================================================== @Override public Branch createBranch(final String branchName) { checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!"); this.assertBranchNameExists(branchName, false); long now = this.getMasterBranch().getTemporalKeyValueStore().getNow(); return this.createBranch(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, branchName, now); } @Override public Branch createBranch(final String branchName, final long branchingTimestamp) { checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!"); this.assertBranchNameExists(branchName, false); checkArgument(branchingTimestamp >= 0, "Precondition violation - argument 'branchingTimestamp' must not be negative!"); long now = this.getMasterBranch().getTemporalKeyValueStore().getNow(); checkArgument(branchingTimestamp <= now, "Precondition violation - argument 'branchingTimestamp' must be less than the timestamp of the latest commit on the parent branch!"); return this.createBranch(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, branchName, branchingTimestamp); } @Override public Branch createBranch(final String parentName, final String newBranchName) { checkNotNull(parentName, "Precondition violation - argument 'parentName' must not be NULL!"); checkNotNull(newBranchName, "Precondition violation - argument 'newBranchName' must not be NULL!"); this.assertBranchNameExists(newBranchName, false); this.assertBranchNameExists(parentName, true); long now = this.getBranchInternal(parentName).getTemporalKeyValueStore().getNow(); return this.createBranch(parentName, newBranchName, now); } @Override public Branch createBranch(final String parentName, final String newBranchName, final long branchingTimestamp) { checkNotNull(parentName, "Precondition violation - argument 'parentName' must not be NULL!"); checkNotNull(newBranchName, "Precondition violation - argument 'newBranchName' must not be NULL!"); this.assertBranchNameExists(parentName, true); this.assertBranchNameExists(newBranchName, false); checkArgument(branchingTimestamp >= 0, "Precondition violation - argument 'branchingTimestamp' must not be negative!"); long now = this.getBranchInternal(parentName).getTemporalKeyValueStore().getNow(); checkArgument(branchingTimestamp <= now, "Precondition violation - argument 'branchingTimestamp' must be less than the timestamp of the latest commit on the parent branch!"); String directoryName = this.dirNameResolver.createDirectoryNameForBranchName(newBranchName); IBranchMetadata metadata = IBranchMetadata.create(newBranchName, parentName, branchingTimestamp, directoryName); Branch createdBranch = this.createBranch(metadata); for (BranchEventListener eventListener : this.eventListeners) { eventListener.onBranchCreated(createdBranch); } return createdBranch; } @Override public boolean existsBranch(final String branchName) { checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!"); return this.getBranchInternal(branchName) != null; } @Override public BranchInternal getBranch(final String branchName) { checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!"); this.assertBranchNameExists(branchName, true); return this.getBranchInternal(branchName); } @Override public Set<Branch> getBranches() { Set<Branch> resultSet = Sets.newHashSet(); for (String branchName : this.getBranchNames()) { Branch branch = this.getBranch(branchName); resultSet.add(branch); } return Collections.unmodifiableSet(resultSet); } @Override public List<Branch> getChildBranches(final Branch branch, final boolean recursive) { try (AutoLock lock = this.getOwningDB().lockNonExclusive()) { if (recursive) { return this.getChildBranchesRecursively(branch, false); } else { return this.getBranches().stream() .filter(b -> Objects.equals(branch.getName(), b.getMetadata().getParentName())) .collect(Collectors.toList()); } } } @Override public List<String> deleteBranchRecursively(final String branchName) { checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!"); checkArgument(!branchName.equals(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER), "Precondition violation - the master branch cannot be deleted!"); try (AutoLock lock = this.getOwningDB().lockExclusive()) { BranchInternal branchToDelete = this.getBranch(branchName); if (branchToDelete == null) { // there is no branch to delete return Collections.emptyList(); } List<Branch> branchesToDelete = this.getChildBranchesRecursively(branchToDelete, true); List<String> deletedBranches = Lists.newArrayList(); // first delete all indices for (Branch deletedBranch : branchesToDelete) { for (BranchEventListener eventListener : this.eventListeners) { eventListener.onBranchDeleted(deletedBranch); } } // then start deleting in the child branch for (Branch childBranchToDelete : Lists.reverse(branchesToDelete)) { this.deleteSingleBranch(childBranchToDelete); deletedBranches.add(childBranchToDelete.getName()); } return Collections.unmodifiableList(deletedBranches); } } @NotNull private List<Branch> getChildBranchesRecursively(final Branch rootBranch, boolean includeSelf) { // find the child branches, recursively Set<Branch> allBranchesExceptMaster = this.getBranches().stream() .filter(b -> ChronoDBConstants.MASTER_BRANCH_IDENTIFIER.equals(b.getName()) == false) .collect(Collectors.toSet()); ListMultimap<String, Branch> branchesByParentName = Multimaps.index( allBranchesExceptMaster, branch -> branch.getMetadata().getParentName() ); Queue<Branch> toVisit = new LinkedBlockingQueue<>(); List<Branch> resultList = Lists.newArrayList(); toVisit.add(rootBranch); while (!toVisit.isEmpty()) { Branch branch = toVisit.poll(); if (includeSelf || !rootBranch.equals(branch)) { resultList.add(branch); } List<Branch> childBranches = branchesByParentName.get(branch.getName()); toVisit.addAll(childBranches); } return resultList; } @Override public Branch getActualBranchForQuerying(@NotNull final String branchName, final long timestamp) { checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!"); checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be NULL!"); Branch currentBranch = this.getBranch(branchName); if (currentBranch == null) { throw new IllegalArgumentException("Precondition violation - argument 'branchName' refers to a non-existing branch '" + branchName + "'!"); } while (!currentBranch.isMaster() && currentBranch.getBranchingTimestamp() >= timestamp) { currentBranch = currentBranch.getOrigin(); } return currentBranch; } // ===================================================================================================================== // INTERNAL API // ===================================================================================================================== @Override public void addBranchEventListener(final BranchEventListener listener) { checkNotNull(listener, "Precondition violation - argument 'listener' must not be NULL!"); this.eventListeners.add(listener); } @Override public void removeBranchEventListener(final BranchEventListener listener) { checkNotNull(listener, "Precondition violation - argument 'listener' must not be NULL!"); this.eventListeners.remove(listener); } @Override public void loadBranchDataFromDump(final List<IBranchMetadata> branches) { checkNotNull(branches, "Precondition violation - argument 'branches' must not be NULL!"); for (IBranchMetadata branchMetadata : branches) { // assert that the branch does not yet exist if (this.existsBranch(branchMetadata.getName())) { throw new IllegalStateException( "There already exists a branch named '" + branchMetadata.getName() + "'!"); } // assert that the parent branch does exist if (this.existsBranch(branchMetadata.getParentName()) == false) { throw new IllegalStateException( "Attempted to create branch '" + branchMetadata.getName() + "' on parent '" + branchMetadata.getParentName() + "', but the parent branch does not exist!"); } this.createBranch(branchMetadata); } } protected abstract void deleteSingleBranch(Branch branch); // ===================================================================================================================== // INTERNAL HELPER METHODS // ===================================================================================================================== @Override public BranchInternal getMasterBranch() { // this override is convenient because it returns the BranchInternal representation of the branch. return this.getBranchInternal(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER); } protected void assertBranchNameExists(final String branchName, final boolean exists) { if (exists) { if (this.existsBranch(branchName) == false) { throw new ChronoDBBranchingException("There is no branch named '" + branchName + "'!"); } } else { if (this.existsBranch(branchName)) { throw new ChronoDBBranchingException("A branch with name '" + branchName + "' already exists!"); } } } // ===================================================================================================================== // ABSTRACT METHOD DECLARATIONS // ===================================================================================================================== protected abstract BranchInternal createBranch(IBranchMetadata metadata); protected abstract BranchInternal getBranchInternal(final String name); protected abstract ChronoDBInternal getOwningDB(); }
13,594
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AbstractCommitMetadataStore.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/engines/base/AbstractCommitMetadataStore.java
package org.chronos.chronodb.internal.impl.engines.base; import static com.google.common.base.Preconditions.*; import java.util.Comparator; import java.util.List; import java.util.Map.Entry; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.stream.Collectors; import org.apache.commons.lang3.tuple.Pair; import org.chronos.chronodb.api.Branch; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.SerializationManager; import org.chronos.chronodb.internal.api.CommitMetadataStore; public abstract class AbstractCommitMetadataStore implements CommitMetadataStore { private final ChronoDB owningDB; private final Branch owningBranch; private final ReadWriteLock lock; protected AbstractCommitMetadataStore(final ChronoDB owningDB, final Branch owningBranch) { checkNotNull(owningDB, "Precondition violation - argument 'owningDB' must not be NULL!"); checkNotNull(owningBranch, "Precondition violation - argument 'owningBranch' must not be NULL!"); this.owningDB = owningDB; this.owningBranch = owningBranch; this.lock = new ReentrantReadWriteLock(true); } @Override public void put(final long commitTimestamp, final Object commitMetadata) { checkArgument(commitTimestamp >= 0, "Precondition violation - argument 'commitTimestamp' must not be negative!"); // serialize the metadata object byte[] serializedMetadata = this.serialize(commitMetadata); this.lock.writeLock().lock(); try { this.putInternal(commitTimestamp, serializedMetadata); } finally { this.lock.writeLock().unlock(); } } @Override public Object get(final long commitTimestamp) { checkArgument(commitTimestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); byte[] serializedValue = null; this.lock.readLock().lock(); try { // retrieve the byte array result serializedValue = this.getInternal(commitTimestamp); } finally { this.lock.readLock().unlock(); } if (serializedValue == null || serializedValue.length <= 0) { // in this case we couldn't find a commit, or the assigned metadata was null. return null; } else { // we found a commit with metadata; deserialize the value and return it return this.getSerializationManager().deserialize(serializedValue); } } @Override public List<Long> getCommitTimestampsAround(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!"); return this.getCommitMetadataAround(timestamp, count, includeSystemInternalCommits).stream().map(entry -> entry.getKey()).collect(Collectors.toList()); } @Override public List<Long> getCommitTimestampsBefore(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!"); return this.getCommitMetadataBefore(timestamp, count, includeSystemInternalCommits).stream().map(entry -> entry.getKey()).collect(Collectors.toList()); } @Override public List<Long> getCommitTimestampsAfter(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!"); return this.getCommitMetadataAfter(timestamp, count, includeSystemInternalCommits).stream().map(entry -> entry.getKey()).collect(Collectors.toList()); } @Override public void rollbackToTimestamp(final long timestamp) { checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); this.lock.writeLock().lock(); try { this.rollbackToTimestampInternal(timestamp); } finally { this.lock.writeLock().unlock(); } } @Override public Branch getOwningBranch() { return this.owningBranch; } // ===================================================================================================================== // UTILITY METHODS // ===================================================================================================================== protected SerializationManager getSerializationManager() { return this.owningDB.getSerializationManager(); } protected ChronoDB getOwningDB() { return this.owningDB; } protected String getBranchName() { return this.getOwningBranch().getName(); } protected <A, B> Pair<A, B> mapEntryToPair(final Entry<A, B> entry) { return Pair.of(entry.getKey(), entry.getValue()); } @SuppressWarnings("unchecked") protected <A, B> Pair<A, B> mapSerialEntryToPair(final Entry<A, byte[]> entry) { return (Pair<A, B>) Pair.of(entry.getKey(), this.deserialize(entry.getValue())); } protected byte[] serialize(final Object value) { if (value == null) { // serialize NULL values as byte arrays of length 0 return new byte[0]; } return this.getSerializationManager().serialize(value); } protected Object deserialize(final byte[] serialForm) { if (serialForm == null || serialForm.length <= 0) { return null; } return this.getSerializationManager().deserialize(serialForm); } protected Entry<Long, Object> deserializeValueOf(final Entry<Long, byte[]> entry) { if (entry.getValue() == null) { return Pair.of(entry.getKey(), null); } else { return Pair.of(entry.getKey(), this.deserialize(entry.getValue())); } } // ===================================================================================================================== // ABSTRAC METHOD DECLARATIONS // ===================================================================================================================== protected abstract byte[] getInternal(long timestamp); protected abstract void putInternal(long commitTimestamp, byte[] metadata); protected abstract void rollbackToTimestampInternal(long timestamp); // ================================================================================================================= // INNER CLASSES // ================================================================================================================= protected static class EntryTimestampComparator implements Comparator<Entry<Long, ?>> { public static final EntryTimestampComparator INSTANCE = new EntryTimestampComparator(); @Override public int compare(final Entry<Long, ?> o1, final Entry<Long, ?> o2) { if (o1 == null && o2 == null) { return 0; } else if (o1 != null && o2 == null) { return 1; } else if (o1 == null && o2 != null) { return -1; } return o1.getKey().compareTo(o2.getKey()); } } }
6,981
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
TemporalKeyImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/temporal/TemporalKeyImpl.java
package org.chronos.chronodb.internal.impl.temporal; import static com.google.common.base.Preconditions.*; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.api.key.TemporalKey; public final class TemporalKeyImpl /* NOT extends QualifiedKeyImpl */ implements TemporalKey { private long timestamp; private String keyspace; private String key; protected TemporalKeyImpl() { // default constructor for serialization purposes } public TemporalKeyImpl(final long timestamp, final String keyspace, final String key) { checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); this.timestamp = timestamp; this.keyspace = keyspace; this.key = key; } // ===================================================================================================================== // GETTERS // ===================================================================================================================== @Override public long getTimestamp() { return this.timestamp; } @Override public String getKeyspace() { return this.keyspace; } @Override public String getKey() { return this.key; } // ===================================================================================================================== // CONVERSION METHODS // ===================================================================================================================== @Override public QualifiedKey toQualifiedKey() { return QualifiedKey.create(this.keyspace, this.key); } // ===================================================================================================================== // HASH CODE & EQUALS // ===================================================================================================================== @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.key == null ? 0 : this.key.hashCode()); result = prime * result + (this.keyspace == null ? 0 : this.keyspace.hashCode()); result = prime * result + (int) (this.timestamp ^ this.timestamp >>> 32); 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; } TemporalKeyImpl other = (TemporalKeyImpl) obj; if (this.key == null) { if (other.key != null) { return false; } } else if (!this.key.equals(other.key)) { return false; } if (this.keyspace == null) { if (other.keyspace != null) { return false; } } else if (!this.keyspace.equals(other.keyspace)) { return false; } if (this.timestamp != other.timestamp) { return false; } return true; } // ===================================================================================================================== // TOSTRING // ===================================================================================================================== @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("TK['"); builder.append(this.getKeyspace()); builder.append("->"); builder.append(this.getKey()); builder.append("'@"); if (this.timestamp == Long.MAX_VALUE) { builder.append("MAX"); } else if (this.timestamp <= 0) { builder.append("MIN"); } else { builder.append(this.timestamp); } builder.append("]"); return builder.toString(); } // ===================================================================================================================== // COMPARISON // ===================================================================================================================== // @Override // public int compareTo(final TemporalKey o) { // if (this.getKey().equals(o.getKey())) { // if (this.getOperationTimestamp() == o.getOperationTimestamp()) { // return 0; // } // if (this.getOperationTimestamp() > o.getOperationTimestamp()) { // return 1; // } // return -1; // } // int comparisonValue = this.getKey().compareTo(o.getKey()); // if (comparisonValue < 0) { // return -1; // } else if (comparisonValue == 0) { // return 0; // } else { // return 1; // } // } }
4,477
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
UnqualifiedTemporalKey.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/temporal/UnqualifiedTemporalKey.java
package org.chronos.chronodb.internal.impl.temporal; import static com.google.common.base.Preconditions.*; import java.io.Serializable; import com.google.common.base.Strings; import org.chronos.chronodb.api.key.TemporalKey; public class UnqualifiedTemporalKey implements Serializable, Comparable<UnqualifiedTemporalKey> { private static final char SEPARATOR = '@'; public static UnqualifiedTemporalKey create(final String key, final long timestamp) { return new UnqualifiedTemporalKey(key, timestamp); } public static UnqualifiedTemporalKey createMin(final String key) { return new UnqualifiedTemporalKey(key, 0L); } public static UnqualifiedTemporalKey createMax(final String key) { return new UnqualifiedTemporalKey(key, Long.MAX_VALUE); } public static UnqualifiedTemporalKey createMin(final UnqualifiedTemporalKey key) { return new UnqualifiedTemporalKey(key.getKey(), 0L); } public static UnqualifiedTemporalKey createMax(final UnqualifiedTemporalKey key) { return new UnqualifiedTemporalKey(key.getKey(), Long.MAX_VALUE); } public static UnqualifiedTemporalKey parseSerializableFormat(final String serializedFormat) { checkNotNull(serializedFormat, "Precondition violation - argument 'serializedFormat' must not be NULL!"); int separatorIndex = serializedFormat.lastIndexOf(SEPARATOR); if (separatorIndex == -1) { throw new IllegalArgumentException( "The string '" + serializedFormat + "' is no valid serial form of an UnqualifiedTemporalKey!"); } try { String key = serializedFormat.substring(0, separatorIndex); String timestamp = serializedFormat.substring(separatorIndex + 1, serializedFormat.length()); // remove leading zeroes timestamp = timestamp.replaceFirst("^0+(?!$)", ""); long timestampValue = Long.parseLong(timestamp); return new UnqualifiedTemporalKey(key, timestampValue); } catch (NumberFormatException e) { throw new IllegalArgumentException( "The string '" + serializedFormat + "' is no valid serial form of an UnqualifiedTemporalKey!", e); } } private final String key; private final long timestamp; public UnqualifiedTemporalKey(final String key, final long timestamp) { this.key = key; this.timestamp = timestamp; } public String getKey() { return this.key; } public long getTimestamp() { return this.timestamp; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.key == null ? 0 : this.key.hashCode()); result = prime * result + (int) (this.timestamp ^ this.timestamp >>> 32); 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; } UnqualifiedTemporalKey other = (UnqualifiedTemporalKey) obj; if (this.key == null) { if (other.key != null) { return false; } } else if (!this.key.equals(other.key)) { return false; } if (this.timestamp != other.timestamp) { return false; } return true; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("K['"); builder.append(this.getKey()); builder.append("'@"); if (this.timestamp == Long.MAX_VALUE) { builder.append("MAX"); } else if (this.timestamp <= 0) { builder.append("MIN"); } else { builder.append(this.timestamp); } builder.append("]"); return builder.toString(); } @Override public int compareTo(final UnqualifiedTemporalKey o) { if (this.getKey().equals(o.getKey())) { if (this.getTimestamp() == o.getTimestamp()) { return 0; } if (this.getTimestamp() > o.getTimestamp()) { return 1; } return -1; } int comparisonValue = this.getKey().compareTo(o.getKey()); if (comparisonValue < 0) { return -1; } else if (comparisonValue == 0) { return 0; } else { return 1; } } public String toSerializableFormat() { String timestampString = Strings.padStart(String.valueOf(this.timestamp), 19, '0'); return this.key + SEPARATOR + timestampString; } public InverseUnqualifiedTemporalKey inverse(){ return InverseUnqualifiedTemporalKey.create(this.timestamp, this.key); } public TemporalKey toTemporalKey(String keyspace){ checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); return TemporalKey.create(this.timestamp, keyspace, this.key); } }
4,456
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
UnqualifiedTemporalEntry.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/temporal/UnqualifiedTemporalEntry.java
package org.chronos.chronodb.internal.impl.temporal; import java.util.Arrays; public class UnqualifiedTemporalEntry implements Comparable<UnqualifiedTemporalEntry> { private final UnqualifiedTemporalKey key; private final byte[] value; public UnqualifiedTemporalEntry(final UnqualifiedTemporalKey key, final byte[] value) { this.key = key; this.value = value; } public UnqualifiedTemporalKey getKey() { return this.key; } public byte[] getValue() { return this.value; } @Override public int compareTo(UnqualifiedTemporalEntry o) { if (o == null) { return 1; } return this.getKey().compareTo(o.getKey()); } @Override public String toString() { final StringBuilder sb = new StringBuilder("UnqualifiedTemporalEntry{"); sb.append("key=").append(key); sb.append(", value=").append(Arrays.toString(value)); sb.append('}'); return sb.toString(); } }
892
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
InverseUnqualifiedTemporalKey.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/temporal/InverseUnqualifiedTemporalKey.java
package org.chronos.chronodb.internal.impl.temporal; import static com.google.common.base.Preconditions.*; import java.io.Serializable; import com.google.common.base.Strings; import org.chronos.chronodb.api.key.TemporalKey; public class InverseUnqualifiedTemporalKey implements Serializable, Comparable<InverseUnqualifiedTemporalKey> { private static final char SEPARATOR = '#'; public static InverseUnqualifiedTemporalKey create(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!"); return new InverseUnqualifiedTemporalKey(timestamp, key); } public static InverseUnqualifiedTemporalKey createMinInclusive(final long timestamp) { checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); return new InverseUnqualifiedTemporalKey(timestamp, ""); } public static InverseUnqualifiedTemporalKey createMaxExclusive(final long timestamp) { return new InverseUnqualifiedTemporalKey(timestamp + 1, ""); } public static InverseUnqualifiedTemporalKey parseSerializableFormat(final String serializedFormat) { checkNotNull(serializedFormat, "Precondition violation - argument 'serializedFormat' must not be NULL!"); int separatorIndex = serializedFormat.indexOf(SEPARATOR); if (separatorIndex == -1) { throw new IllegalArgumentException( "The string '" + serializedFormat + "' is no valid serial form of an InverseUnqualifiedTemporalKey!"); } try { String key = serializedFormat.substring(separatorIndex + 1, serializedFormat.length()); String timestamp = serializedFormat.substring(0, separatorIndex); // remove leading zeroes timestamp = timestamp.replaceFirst("^0+(?!$)", ""); long timestampValue = Long.parseLong(timestamp); return new InverseUnqualifiedTemporalKey(timestampValue, key); } catch (NumberFormatException e) { throw new IllegalArgumentException( "The string '" + serializedFormat + "' is no valid serial form of an InverseUnqualifiedTemporalKey!", e); } } private final String key; private final long timestamp; public InverseUnqualifiedTemporalKey(final long timestamp, final String key) { this.timestamp = timestamp; this.key = key; } public String getKey() { return this.key; } public long getTimestamp() { return this.timestamp; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.key == null ? 0 : this.key.hashCode()); result = prime * result + (int) (this.timestamp ^ this.timestamp >>> 32); 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; } InverseUnqualifiedTemporalKey other = (InverseUnqualifiedTemporalKey) obj; if (this.key == null) { if (other.key != null) { return false; } } else if (!this.key.equals(other.key)) { return false; } if (this.timestamp != other.timestamp) { return false; } return true; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("KI['"); if (this.timestamp == Long.MAX_VALUE) { builder.append("MAX"); } else if (this.timestamp <= 0) { builder.append("MIN"); } else { builder.append(this.timestamp); } builder.append("'#"); builder.append(this.getKey()); builder.append("]"); return builder.toString(); } public TemporalKey toTemporalKey(String keyspace){ checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); return TemporalKey.create(timestamp, keyspace, key); } @Override public int compareTo(final InverseUnqualifiedTemporalKey o) { if (this.getTimestamp() == o.getTimestamp()) { int comparisonValue = this.getKey().compareTo(o.getKey()); if (comparisonValue < 0) { return -1; } else if (comparisonValue == 0) { return 0; } else { return 1; } } else if (this.getTimestamp() > o.getTimestamp()) { return 1; } else { return -1; } } public String toSerializableFormat() { String timestampString = Strings.padStart(String.valueOf(this.timestamp), 19, '0'); return timestampString + SEPARATOR + this.key; } public UnqualifiedTemporalKey inverse(){ return UnqualifiedTemporalKey.create(this.key, this.timestamp); } }
4,528
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
PeriodImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/temporal/PeriodImpl.java
package org.chronos.chronodb.internal.impl.temporal; import static com.google.common.base.Preconditions.*; import org.chronos.chronodb.internal.api.Period; public final class PeriodImpl implements Period { // ===================================================================================================================== // CONSTANTS // ===================================================================================================================== private static final long FOREVER = Long.MAX_VALUE; private static final Period EMPTY = new PeriodImpl(0, 0); private static final Period ETERNAL = new PeriodImpl(0, FOREVER); // ===================================================================================================================== // STATIC FACTORY METHODS // ===================================================================================================================== /** * Creates a period that contains a range of timestamps. * * <p> * This method can <b>not</b> be used to create empty periods. Please use {@link #empty()} instead. * * @param lowerBoundInclusive * The lower bound timestamp to be included in the new period. Must not be negative. Must be strictly * smaller than <code>upperBoundExclusive</code>. * @param upperBoundExclusive * The upper bound timestamp to be exclused from the period. Must not be negative. Must be strictly * larger than <code>lowerBoundInclusive</code>. * * @return A new period with the given range of timestamps. */ public static Period createRange(final long lowerBoundInclusive, final long upperBoundExclusive) { checkArgument(lowerBoundInclusive >= 0, "Precondition violation - argument 'lowerBoundInclusive' must not be negative!"); checkArgument(upperBoundExclusive >= 0, "Precondition violation - argument 'upperBoundExclusive' must not be negative!"); if (lowerBoundInclusive >= upperBoundExclusive) { throw new IllegalArgumentException("Precondition violation - argument 'lowerBoundInclusive' (" + lowerBoundInclusive + ") must be strictly smaller than argument 'upperBoundExclusive' (" + upperBoundExclusive + ")!"); } return new PeriodImpl(lowerBoundInclusive, upperBoundExclusive); } /** * Creates a new {@link Period} that contains only one point in time, which is the given timestamp. * * <p> * In other words, {@link #contains(long)} will always return <code>false</code> for all timestamps, except for the * given one. * * <p> * The lower bound of the period will be set to the given timestamp (as it is inclusive), the upper bound will be * set to the given timestamp + 1 (exclusive). * * @param timestamp * The timestamp which should be contained in the resulting period. Must not be negative. * @return A period that contains only the given timestamp. Never <code>null</code>. */ public static Period createPoint(final long timestamp) { checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); return new PeriodImpl(timestamp, timestamp + 1); } /** * Creates a new {@link Period} that starts at the given lower bound (inclusive) and is open-ended. * * <p> * In other words, {@link #contains(long)} will always return <code>true</code> for all timestamps greater than or * equal to the given one. * * <p> * Calling {@link #getUpperBound()} on the resulting period will return {@link Long#MAX_VALUE}. * * @param lowerBound * The lower bound to use for the new range period. Must not be negative. * * @return A period that starts at the given lower bound (inclusive) and is open-ended. */ public static Period createOpenEndedRange(final long lowerBound) { checkArgument(lowerBound >= 0, "Precondition violation - argument 'lowerBound' must not be negative!"); return new PeriodImpl(lowerBound, FOREVER); } /** * Returns an empty period. * * <p> * An empty period is a period where {@link #contains(long)} always returns <code>false</code>, and the * {@link #getLowerBound()} is greater than or equal to {@link #getUpperBound()}. In this implementation, * {@link #getLowerBound()} and {@link #getUpperBound()} both return zero. * * @return The empty period. Never <code>null</code>. */ public static Period empty() { return EMPTY; } /** * Returns the "eternal" period, i.e. the period that contains all non-negative timestamps. * * @return The eternal period. Never <code>null</code>. */ public static Period eternal() { return ETERNAL; } // ===================================================================================================================== // FIELDS // ===================================================================================================================== /** The lower bound of this period (inclusive). Always greater than or equal to zero. Immutable. */ private final long lowerBound; /** The upper bound of this period (exclusive). Always greater than or equal to zero. Immutable. */ private final long upperBound; // ===================================================================================================================== // CONSTRUCTOR // ===================================================================================================================== /** * Creates a new period. * * <p> * There are <b>no checks</b> on the arguments in this constructor. It is assumed that the static factory methods * provided by this class are used, which perform the required checks. * * @param lowerBound * The lower bound to use. * @param upperBound * The upper bound to use. */ private PeriodImpl(final long lowerBound, final long upperBound) { this.lowerBound = lowerBound; this.upperBound = upperBound; } // ===================================================================================================================== // PUBLIC API // ===================================================================================================================== @Override public long getLowerBound() { return this.lowerBound; } @Override public long getUpperBound() { return this.upperBound; } // ===================================================================================================================== // HASH CODE & EQUALS // ===================================================================================================================== @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (this.lowerBound ^ this.lowerBound >>> 32); result = prime * result + (int) (this.upperBound ^ this.upperBound >>> 32); 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; } PeriodImpl other = (PeriodImpl) obj; if (this.lowerBound != other.lowerBound) { return false; } if (this.upperBound != other.upperBound) { return false; } return true; } // ===================================================================================================================== // TOSTRING // ===================================================================================================================== @Override public String toString() { String upperBound = String.valueOf(this.getUpperBound()); if (this.isOpenEnded()) { upperBound = "MAX"; } return "Period[" + this.getLowerBound() + ";" + upperBound + ")"; } }
7,715
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
QualifiedKeyImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/temporal/QualifiedKeyImpl.java
package org.chronos.chronodb.internal.impl.temporal; import static com.google.common.base.Preconditions.*; import org.chronos.chronodb.api.key.QualifiedKey; public final class QualifiedKeyImpl implements QualifiedKey { // ===================================================================================================================== // FIELDS // ===================================================================================================================== private String key; private String keyspace; // ===================================================================================================================== // CONSTRUCTOR // ===================================================================================================================== protected QualifiedKeyImpl() { // default constructor for serialization purposes } public QualifiedKeyImpl(final String keyspace, final String key) { checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); this.key = key; this.keyspace = keyspace; } // ===================================================================================================================== // GETTERS // ===================================================================================================================== @Override public String getKey() { return this.key; } @Override public String getKeyspace() { return this.keyspace; } // ===================================================================================================================== // HASH CODE & EQUALS // ===================================================================================================================== @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.key == null ? 0 : this.key.hashCode()); result = prime * result + (this.keyspace == null ? 0 : this.keyspace.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; } QualifiedKeyImpl other = (QualifiedKeyImpl) obj; if (this.key == null) { if (other.key != null) { return false; } } else if (!this.key.equals(other.key)) { return false; } if (this.keyspace == null) { if (other.keyspace != null) { return false; } } else if (!this.keyspace.equals(other.keyspace)) { return false; } return true; } // ===================================================================================================================== // TOSTRING // ===================================================================================================================== @Override public String toString() { return "QK['" + this.keyspace + "->" + this.key + "']"; } }
3,015
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoIdentifierImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/temporal/ChronoIdentifierImpl.java
package org.chronos.chronodb.internal.impl.temporal; import static com.google.common.base.Preconditions.*; import org.chronos.chronodb.api.key.ChronoIdentifier; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.api.key.TemporalKey; public final class ChronoIdentifierImpl /* NOT extends TemporalKeyImpl */ implements ChronoIdentifier { // ===================================================================================================================== // FIELDS // ===================================================================================================================== private String branch; private long timestamp; private String keyspace; private String key; // ===================================================================================================================== // CONSTRUCTOR // ===================================================================================================================== protected ChronoIdentifierImpl() { // default constructor for serialization purposes } public ChronoIdentifierImpl(final String branch, final String keyspace, final String key, final long timestamp) { checkNotNull(branch, "Precondition violation - argument 'branchName' must not be NULL!"); checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!"); this.branch = branch; this.timestamp = timestamp; this.keyspace = keyspace; this.key = key; } // ===================================================================================================================== // GETTERS // ===================================================================================================================== @Override public String getBranchName() { return this.branch; } @Override public long getTimestamp() { return this.timestamp; } @Override public String getKeyspace() { return this.keyspace; } @Override public String getKey() { return this.key; } // ===================================================================================================================== // CONVERSION METHODS // ===================================================================================================================== @Override public TemporalKey toTemporalKey() { return TemporalKey.create(this.timestamp, this.keyspace, this.key); } @Override public QualifiedKey toQualifiedKey() { return QualifiedKey.create(this.keyspace, this.key); } // ===================================================================================================================== // HASH CODE & EQUALS // ===================================================================================================================== @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.branch == null ? 0 : this.branch.hashCode()); result = prime * result + (this.key == null ? 0 : this.key.hashCode()); result = prime * result + (this.keyspace == null ? 0 : this.keyspace.hashCode()); result = prime * result + (int) (this.timestamp ^ this.timestamp >>> 32); 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; } ChronoIdentifierImpl other = (ChronoIdentifierImpl) obj; if (this.branch == null) { if (other.branch != null) { return false; } } else if (!this.branch.equals(other.branch)) { return false; } if (this.key == null) { if (other.key != null) { return false; } } else if (!this.key.equals(other.key)) { return false; } if (this.keyspace == null) { if (other.keyspace != null) { return false; } } else if (!this.keyspace.equals(other.keyspace)) { return false; } if (this.timestamp != other.timestamp) { return false; } return true; } // ===================================================================================================================== // TOSTRING // ===================================================================================================================== @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("CI['"); builder.append(this.getBranchName()); builder.append("->"); builder.append(this.getKeyspace()); builder.append("->"); builder.append(this.getKey()); builder.append("'@"); if (this.timestamp == Long.MAX_VALUE) { builder.append("MAX"); } else if (this.timestamp <= 0) { builder.append("MIN"); } else { builder.append(this.timestamp); } builder.append("]"); return builder.toString(); } }
4,963
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
GetResultImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/temporal/GetResultImpl.java
package org.chronos.chronodb.internal.impl.temporal; import static com.google.common.base.Preconditions.*; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.internal.api.GetResult; import org.chronos.chronodb.internal.api.Period; public class GetResultImpl<T> implements GetResult<T> { // ===================================================================================================================== // STATIC FACTORY METHODS // ===================================================================================================================== public static <T> GetResult<T> createNoValueResult(final QualifiedKey requestedKey, final Period range) { checkNotNull(requestedKey, "Precondition violation - argument 'requestedKey' must not be NULL!"); checkNotNull(range, "Precondition violation - argument 'range' must not be NULL!"); return new GetResultImpl<T>(requestedKey, null, range, false); } public static <T> GetResult<T> create(final QualifiedKey requestedKey, final T value, final Period range) { checkNotNull(requestedKey, "Precondition violation - argument 'requestedKey' must not be NULL!"); checkNotNull(range, "Precondition violation - argument 'range' must not be NULL!"); return new GetResultImpl<T>(requestedKey, value, range, true); } public static <T> GetResult<T> alterPeriod(final GetResult<T> getResult, final Period newPeriod) { checkNotNull(getResult, "Precondition violation - argument 'getResult' must not be NULL!"); checkNotNull(newPeriod, "Precondition violation - argument 'newPeriod' must not be NULL!"); return new GetResultImpl<T>(getResult.getRequestedKey(), getResult.getValue(), newPeriod, getResult.isHit()); } // ===================================================================================================================== // FIELDS // ===================================================================================================================== private final QualifiedKey requestedKey; private final T value; private final Period range; private final boolean isHit; // ===================================================================================================================== // CONSTRUCTOR // ===================================================================================================================== private GetResultImpl(final QualifiedKey requestedKey, final T value, final Period range, final boolean isHit) { checkNotNull(requestedKey, "Precondition violation - argument 'requestedKey' must not be NULL!"); checkNotNull(range, "Precondition violation - argument 'range' must not be NULL!"); this.requestedKey = requestedKey; this.value = value; this.range = range; this.isHit = isHit; } // ===================================================================================================================== // PUBLIC API // ===================================================================================================================== @Override public QualifiedKey getRequestedKey() { return this.requestedKey; } @Override public Period getPeriod() { return this.range; } @Override public T getValue() { return this.value; } @Override public boolean isHit() { return this.isHit; } @Override public String toString() { return "GetResult[key=" + this.requestedKey + ", period=" + this.getPeriod() + ", value=" + this.getValue() + ", isHit=" + this.isHit() + "]"; } }
3,493
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
MigrationChainImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/migration/MigrationChainImpl.java
package org.chronos.chronodb.internal.impl.migration; import com.google.common.collect.Lists; import com.google.common.reflect.ClassPath; import com.google.common.reflect.ClassPath.ClassInfo; import org.chronos.chronodb.internal.api.ChronoDBInternal; import org.chronos.chronodb.internal.api.migration.ChronosMigration; import org.chronos.chronodb.internal.api.migration.MigrationChain; import org.chronos.chronodb.internal.api.migration.annotations.Migration; import org.chronos.common.exceptions.ChronosIOException; import org.chronos.common.version.ChronosVersion; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.*; public final class MigrationChainImpl<DBTYPE extends ChronoDBInternal> implements MigrationChain<DBTYPE> { private static final Logger log = LoggerFactory.getLogger(MigrationChainImpl.class); // ================================================================================================================= // STATIC FACTORY METHODS // ================================================================================================================= private static final Map<String, MigrationChain<?>> PACKAGE_TO_MIGRATION_CHAIN = new HashMap<>(); @SuppressWarnings("unchecked") public static synchronized <DBTYPE extends ChronoDBInternal> MigrationChain<DBTYPE> fromPackage(final String qualifiedPackageName) { checkNotNull(qualifiedPackageName, "Precondition violation - argument 'qualifiedPackageName' must not be NULL!"); MigrationChain<?> cachedChain = PACKAGE_TO_MIGRATION_CHAIN.get(qualifiedPackageName); if (cachedChain != null) { return (MigrationChain<DBTYPE>) cachedChain; } try { Set<ClassInfo> topLevelClasses = ClassPath.from(Thread.currentThread().getContextClassLoader()) // get the top level classes of the migration package .getTopLevelClasses(qualifiedPackageName); Set<Class<? extends ChronosMigration<DBTYPE>>> classes = topLevelClasses // stream the class info objects .stream() // load the classes .map(ClassInfo::load) // only consider @Migration classes .filter(clazz -> clazz.getAnnotation(Migration.class) != null) // only consider subclasses of ChronosMigration .filter(ChronosMigration.class::isAssignableFrom) // cast the classes to subclass of chronos migration .map(clazz -> (Class<? extends ChronosMigration<DBTYPE>>) clazz) // collect them in a set .collect(Collectors.toSet()); MigrationChain<DBTYPE> chain = new MigrationChainImpl<>(classes); PACKAGE_TO_MIGRATION_CHAIN.put(qualifiedPackageName, chain); return chain; } catch (IOException e) { throw new ChronosIOException("Failed to scan classpath for ChronosMigration classes! See root cause for details.", e); } } // ================================================================================================================= // FIELDS // ================================================================================================================= private final List<Class<? extends ChronosMigration<DBTYPE>>> classes; // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= private MigrationChainImpl(final Collection<Class<? extends ChronosMigration<DBTYPE>>> migrationClasses) { checkNotNull(migrationClasses, "Precondition violation - argument 'migrationClasses' must not be NULL!"); List<Class<? extends ChronosMigration<DBTYPE>>> classes = Lists.newArrayList(migrationClasses); classes.sort(MigrationClassComparator.INSTANCE); this.classes = Collections.unmodifiableList(classes); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @NotNull @Override public Iterator<Class<? extends ChronosMigration<DBTYPE>>> iterator() { return this.classes.iterator(); } @Override public List<Class<? extends ChronosMigration<DBTYPE>>> getMigrationClasses() { return this.classes; } @Override public MigrationChain<DBTYPE> startingAt(final ChronosVersion from) { return new MigrationChainImpl<>(this.classes.stream().filter(clazz -> { ChronosVersion classFrom = ChronosVersion.parse(clazz.getAnnotation(Migration.class).from()); return classFrom.compareTo(from) >= 0; }).collect(Collectors.toList())); } @Override public void execute(final DBTYPE chronoDB) { for (Class<? extends ChronosMigration<DBTYPE>> migrationClass : this) { // create an instance of the migration final ChronosMigration<DBTYPE> migration = instantiateMigration(migrationClass); try { log.info("Migrating ChronoDB from " + MigrationClassUtil.from(migrationClass) + " to " + MigrationClassUtil.to(migrationClass) + " ..."); // execute the migration migration.execute(chronoDB); // update the chronos version chronoDB.updateChronosVersionTo(MigrationClassUtil.to(migrationClass)); log.info("Migration of ChronoDB from " + MigrationClassUtil.from(migrationClass) + " to " + MigrationClassUtil.to(migrationClass) + " completed successfully."); } catch (Throwable t) { throw new IllegalStateException("Failed to execute migration of class '" + migrationClass.getName() + "'!", t); } } } @NotNull private ChronosMigration<DBTYPE> instantiateMigration(final Class<? extends ChronosMigration<DBTYPE>> migrationClass) { final ChronosMigration<DBTYPE> migration; try { migration = migrationClass.getConstructor().newInstance(); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { throw new IllegalStateException("Failed to instantiate migration class '" + migrationClass.getName() + "'!", e); } return migration; } }
7,056
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
MigrationClassComparator.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/migration/MigrationClassComparator.java
package org.chronos.chronodb.internal.impl.migration; import org.chronos.chronodb.internal.api.ChronoDBInternal; import org.chronos.chronodb.internal.api.migration.ChronosMigration; import org.chronos.chronodb.internal.api.migration.annotations.Migration; import org.chronos.common.version.ChronosVersion; import java.util.Comparator; public final class MigrationClassComparator implements Comparator<Class<? extends ChronosMigration<? extends ChronoDBInternal>>> { public static final MigrationClassComparator INSTANCE = new MigrationClassComparator(); private MigrationClassComparator() { // should be a singleton, thus private constructor } @Override public int compare(final Class<? extends ChronosMigration<? extends ChronoDBInternal>> o1, final Class<? extends ChronosMigration<? extends ChronoDBInternal>> o2) { if (o1 == null && o2 == null) { return 0; } else if (o1 != null && o2 == null) { return 1; } else if (o1 == null && o2 != null) { return -1; } Migration annotation1 = o1.getAnnotation(Migration.class); Migration annotation2 = o2.getAnnotation(Migration.class); ChronosVersion from1 = ChronosVersion.parse(annotation1.from()); ChronosVersion to1 = ChronosVersion.parse(annotation1.to()); ChronosVersion from2 = ChronosVersion.parse(annotation2.from()); ChronosVersion to2 = ChronosVersion.parse(annotation2.to()); if (from1.isGreaterThan(to1)) { throw new IllegalStateException("Migration annotation error on class '" + o1.getName() + "': cannot migrate from '" + from1 + "' to '" + to1 + "' - 'to' is smaller than or equal to 'from'!"); } if (from2.isGreaterThan(to2)) { throw new IllegalStateException("Migration annotation error on class '" + o2.getName() + "': cannot migrate from '" + from2 + "' to '" + to2 + "' - 'to' is smaller than or equal to 'from'!"); } if (from1.equals(from2)) { throw new IllegalStateException("Migration annotation error: classes '" + o1.getName() + "' and '" + o2.getName() + "' specify the same 'from' version: '" + from1 + "'."); } if (to1.equals(to2)) { throw new IllegalStateException("Migration annotation error: classes '" + o1.getName() + "' and '" + o2.getName() + "' specify the same 'to' version: '" + to1 + "'."); } // overlap checks if (from1.isSmallerThan(from2) && to1.isGreaterThan(to2)) { throw new IllegalStateException("Migration annotation error: classes '" + o1.getName() + "' and '" + o2.getName() + "' have overlapping version ranges!"); } if (from2.isSmallerThan(from1) && to2.isGreaterThan(to1)) { throw new IllegalStateException("Migration annotation error: classes '" + o1.getName() + "' and '" + o2.getName() + "' have overlapping version ranges!"); } if (from1.isGreaterThan(from2) && to1.isGreaterThanOrEqualTo(from2)) { return 1; } if (from1.isSmallerThan(from2) && to1.isSmallerThanOrEqualTo(from2)) { return -1; } throw new IllegalStateException("Failed to order migration classes '" + o1.getName() + "' (from: '" + from1 + "' to '" + to1 + "') and '" + o2.getName() + "' (from: '" + from2 + "' to '" + to2 + "')!"); } }
3,399
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
MigrationClassUtil.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/migration/MigrationClassUtil.java
package org.chronos.chronodb.internal.impl.migration; import static com.google.common.base.Preconditions.*; import org.chronos.chronodb.internal.api.migration.ChronosMigration; import org.chronos.chronodb.internal.api.migration.annotations.Migration; import org.chronos.common.version.ChronosVersion; public class MigrationClassUtil { public static ChronosVersion from(final Class<? extends ChronosMigration<?>> migrationClass) { checkNotNull(migrationClass, "Precondition violation - argument 'migrationClass' must not be NULL!"); Migration annotation = migrationClass.getAnnotation(Migration.class); if (annotation == null) { throw new IllegalArgumentException("Failed to read 'Migration' annotation from migration class '" + migrationClass.getName() + "'!"); } return ChronosVersion.parse(annotation.from()); } public static ChronosVersion to(final Class<? extends ChronosMigration<?>> migrationClass) { checkNotNull(migrationClass, "Precondition violation - argument 'migrationClass' must not be NULL!"); Migration annotation = migrationClass.getAnnotation(Migration.class); if (annotation == null) { throw new IllegalArgumentException("Failed to read 'Migration' annotation from migration class '" + migrationClass.getName() + "'!"); } return ChronosVersion.parse(annotation.to()); } }
1,326
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
TextMatchMode.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/TextMatchMode.java
package org.chronos.chronodb.internal.impl.query; import org.chronos.chronodb.api.query.Condition; /** * A simple enumeration that decides how to match a text query against the index. * * <p> * Usually used in conjunction with a {@link Condition}. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public enum TextMatchMode { /** Strict text matching (i.e. respecting upper- & lowercase differences). */ STRICT, /** Case insensitive matching. */ CASE_INSENSITIVE; }
509
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
DoubleSearchSpecificationImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/DoubleSearchSpecificationImpl.java
package org.chronos.chronodb.internal.impl.query; import org.chronos.chronodb.api.SecondaryIndex; import org.chronos.chronodb.api.query.NumberCondition; import org.chronos.chronodb.internal.api.query.searchspec.DoubleSearchSpecification; import org.chronos.chronodb.internal.api.query.searchspec.SearchSpecification; import java.util.function.Predicate; public class DoubleSearchSpecificationImpl extends AbstractSearchSpecification<Double, NumberCondition, Double> implements DoubleSearchSpecification { // ================================================================================================================= // FIELDS // ================================================================================================================= private final double equalityTolerance; // ================================================================================================================= // CONSTRUCTORS // ================================================================================================================= public DoubleSearchSpecificationImpl(final SecondaryIndex index, final NumberCondition condition, final double searchValue, final double equalityTolerance) { super(index, condition, searchValue); this.equalityTolerance = equalityTolerance; } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public double getEqualityTolerance() { return this.equalityTolerance; } @Override public Predicate<Object> toFilterPredicate() { return (obj) -> { if (obj instanceof Double == false) { return false; } double value = (double) obj; return this.condition.applies(value, this.searchValue, this.equalityTolerance); }; } @Override public SearchSpecification<Double, Double> negate() { return new DoubleSearchSpecificationImpl(this.getIndex(), this.getCondition().negate(), this.getSearchValue(), this.getEqualityTolerance()); } @Override protected Class<Double> getElementValueClass() { return Double.class; } @Override public SearchSpecification<Double, Double> onIndex(final SecondaryIndex index) { return new DoubleSearchSpecificationImpl(index, this.condition, this.searchValue, this.equalityTolerance); } // ================================================================================================================= // HASH CODE & EQUALS // ================================================================================================================= @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; DoubleSearchSpecificationImpl that = (DoubleSearchSpecificationImpl) o; return Double.compare(that.equalityTolerance, equalityTolerance) == 0; } @Override public int hashCode() { int result = super.hashCode(); long temp; temp = Double.doubleToLongBits(equalityTolerance); result = 31 * result + (int) (temp ^ (temp >>> 32)); return result; } }
3,522
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
StandardQueryManager.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/StandardQueryManager.java
package org.chronos.chronodb.internal.impl.query; import static com.google.common.base.Preconditions.*; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.builder.query.QueryBuilderFinalizer; import org.chronos.chronodb.api.builder.query.QueryBuilderStarter; import org.chronos.chronodb.internal.api.ChronoDBInternal; import org.chronos.chronodb.internal.api.query.ChronoDBQuery; import org.chronos.chronodb.internal.api.query.QueryManager; import org.chronos.chronodb.internal.api.query.QueryOptimizer; import org.chronos.chronodb.internal.api.query.QueryParser; import org.chronos.chronodb.internal.impl.builder.query.StandardQueryBuilder; import org.chronos.chronodb.internal.impl.builder.query.StandardQueryBuilderFinalizer; import org.chronos.chronodb.internal.impl.query.optimizer.StandardQueryOptimizer; import org.chronos.chronodb.internal.impl.query.parser.StandardQueryParser; public class StandardQueryManager implements QueryManager { private final ChronoDBInternal owningDB; private final StandardQueryParser queryParser; private final StandardQueryOptimizer queryOptimizer; public StandardQueryManager(final ChronoDBInternal owningDB) { checkNotNull(owningDB, "Precondition violation - argument 'owningDB' must not be NULL!"); this.owningDB = owningDB; this.queryParser = new StandardQueryParser(); this.queryOptimizer = new StandardQueryOptimizer(); } @Override public QueryParser getQueryParser() { return this.queryParser; } @Override public QueryOptimizer getQueryOptimizer() { return this.queryOptimizer; } @Override public QueryBuilderStarter createQueryBuilder(final ChronoDBTransaction tx) { checkNotNull(tx, "Precondition violation - argument 'tx' must not be NULL!"); return new StandardQueryBuilder(this.owningDB, tx); } @Override public QueryBuilderFinalizer createQueryBuilderFinalizer(final ChronoDBTransaction tx, final ChronoDBQuery query) { checkNotNull(tx, "Precondition violation - argument 'tx' must not be NULL!"); checkNotNull(query, "Precondition violation - argument 'query' must not be NULL!"); return new StandardQueryBuilderFinalizer(this.owningDB, tx, query); } }
2,189
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
LongSearchSpecificationImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/LongSearchSpecificationImpl.java
package org.chronos.chronodb.internal.impl.query; import com.google.common.base.Preconditions; import org.chronos.chronodb.api.SecondaryIndex; import org.chronos.chronodb.api.query.NumberCondition; import org.chronos.chronodb.internal.api.query.searchspec.LongSearchSpecification; import org.chronos.chronodb.internal.api.query.searchspec.SearchSpecification; import java.util.Objects; import java.util.function.Predicate; public class LongSearchSpecificationImpl extends AbstractSearchSpecification<Long, NumberCondition, Long> implements LongSearchSpecification { // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= public LongSearchSpecificationImpl(final SecondaryIndex index, final NumberCondition condition, final Long searchValue) { super(index, condition, searchValue); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public Predicate<Object> toFilterPredicate() { return (obj) -> { if (obj instanceof Long == false) { return false; } long value = (long) obj; return this.condition.applies(value, this.searchValue); }; } @Override public SearchSpecification<Long, Long> negate() { return new LongSearchSpecificationImpl(this.getIndex(), this.getCondition().negate(), this.getSearchValue()); } @Override protected Class<Long> getElementValueClass() { return Long.class; } @Override public SearchSpecification<Long, Long> onIndex(final SecondaryIndex index) { Preconditions.checkArgument( Objects.equals(index.getName(), this.index.getName()), "Cannot move search specification on the given index - the index names do not match!" ); return new LongSearchSpecificationImpl(index, this.condition, this.searchValue); } // ================================================================================================================= // HASH CODE & EQUALS // ================================================================================================================= @Override public int hashCode() { return super.hashCode() * 31 * this.getClass().hashCode(); } @Override public boolean equals(final Object obj) { if(!super.equals(obj)){ return false; } return this.getClass().equals(obj.getClass()); } }
2,850
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ContainmentLongSearchSpecificationImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/ContainmentLongSearchSpecificationImpl.java
package org.chronos.chronodb.internal.impl.query; import com.google.common.base.Preconditions; import org.chronos.chronodb.api.SecondaryIndex; import org.chronos.chronodb.api.query.LongContainmentCondition; import org.chronos.chronodb.internal.api.query.searchspec.ContainmentLongSearchSpecification; import org.chronos.chronodb.internal.api.query.searchspec.SearchSpecification; import java.util.Objects; import java.util.Set; import java.util.function.Predicate; public class ContainmentLongSearchSpecificationImpl extends AbstractSearchSpecification<Long, LongContainmentCondition, Set<Long>> implements ContainmentLongSearchSpecification { // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= public ContainmentLongSearchSpecificationImpl(final SecondaryIndex index, final LongContainmentCondition condition, final Set<Long> searchValue) { super(index, condition, searchValue); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public Predicate<Object> toFilterPredicate() { return obj -> { if (obj instanceof Long == false) { return false; } long value = (long) obj; return this.condition.applies(value, this.searchValue); }; } @Override public SearchSpecification<Long, Set<Long>> negate() { return new ContainmentLongSearchSpecificationImpl(this.getIndex(), this.condition.negate(), this.searchValue); } @Override protected Class<Long> getElementValueClass() { return Long.class; } @Override public SearchSpecification<Long, Set<Long>> onIndex(final SecondaryIndex index) { Preconditions.checkArgument( Objects.equals(index.getName(), this.index.getName()), "Cannot move search specification on the given index - the index names do not match!" ); return new ContainmentLongSearchSpecificationImpl(index, this.condition, this.searchValue); } // ================================================================================================================= // HASH CODE & EQUALS // ================================================================================================================= @Override public int hashCode() { return super.hashCode() * 31 * this.getClass().hashCode(); } @Override public boolean equals(final Object obj) { if (!super.equals(obj)) { return false; } return this.getClass().equals(obj.getClass()); } }
2,975
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ContainmentDoubleSearchSpecificationImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/ContainmentDoubleSearchSpecificationImpl.java
package org.chronos.chronodb.internal.impl.query; import com.google.common.base.Preconditions; import org.chronos.chronodb.api.SecondaryIndex; import org.chronos.chronodb.api.query.DoubleContainmentCondition; import org.chronos.chronodb.internal.api.query.searchspec.ContainmentDoubleSearchSpecification; import org.chronos.chronodb.internal.api.query.searchspec.SearchSpecification; import java.util.Objects; import java.util.Set; import java.util.function.Predicate; public class ContainmentDoubleSearchSpecificationImpl extends AbstractSearchSpecification<Double, DoubleContainmentCondition, Set<Double>> implements ContainmentDoubleSearchSpecification { // ================================================================================================================= // FIELDS // ================================================================================================================= private final double equalityTolerance; // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= public ContainmentDoubleSearchSpecificationImpl(final SecondaryIndex index, final DoubleContainmentCondition condition, final Set<Double> searchValue, double equalityTolerance) { super(index, condition, searchValue); this.equalityTolerance = equalityTolerance; } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public double getEqualityTolerance() { return this.equalityTolerance; } @Override public Predicate<Object> toFilterPredicate() { return obj -> { if(obj instanceof Double == false){ return false; } double value = (double)obj; return this.condition.applies(value, this.searchValue, this.equalityTolerance); }; } @Override public SearchSpecification<Double, Set<Double>> negate() { return new ContainmentDoubleSearchSpecificationImpl(this.getIndex(), this.condition.negate(), this.searchValue, this.equalityTolerance); } @Override protected Class<Double> getElementValueClass() { return Double.class; } @Override public SearchSpecification<Double, Set<Double>> onIndex(final SecondaryIndex index) { Preconditions.checkArgument( Objects.equals(index.getName(), this.index.getName()), "Cannot move search specification on the given index - the index names do not match!" ); return new ContainmentDoubleSearchSpecificationImpl(index, this.condition, this.searchValue, this.equalityTolerance); } // ================================================================================================================= // HASHCODE, EQUALS // ================================================================================================================= @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; ContainmentDoubleSearchSpecificationImpl that = (ContainmentDoubleSearchSpecificationImpl) o; return Double.compare(that.equalityTolerance, equalityTolerance) == 0; } @Override public int hashCode() { int result = super.hashCode(); long temp; temp = Double.doubleToLongBits(equalityTolerance); result = 31 * result + (int) (temp ^ (temp >>> 32)); return result; } }
3,940
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
StringSearchSpecificationImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/StringSearchSpecificationImpl.java
package org.chronos.chronodb.internal.impl.query; import static com.google.common.base.Preconditions.*; import java.util.Objects; import java.util.Set; import java.util.function.Predicate; import com.google.common.base.Preconditions; import org.chronos.chronodb.api.SecondaryIndex; import org.chronos.chronodb.api.query.StringCondition; import org.chronos.chronodb.internal.api.query.searchspec.SearchSpecification; import org.chronos.chronodb.internal.api.query.searchspec.StringSearchSpecification; public class StringSearchSpecificationImpl extends AbstractSearchSpecification<String, StringCondition, String> implements StringSearchSpecification { // ================================================================================================================= // FIELDS // ================================================================================================================= protected final TextMatchMode matchMode; // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= public StringSearchSpecificationImpl(final SecondaryIndex index, final StringCondition condition, final String searchValue, final TextMatchMode matchMode) { super(index, condition, searchValue); checkNotNull(matchMode, "Precondition violation - argument 'matchMode' must not be NULL!"); this.matchMode = matchMode; } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public TextMatchMode getMatchMode() { return this.matchMode; } @Override public Predicate<Object> toFilterPredicate() { return (obj) -> { if (obj instanceof String == false) { return false; } String value = (String) obj; return this.condition.applies(value, this.searchValue, this.matchMode); }; } @Override public SearchSpecification<String, String> negate() { return new StringSearchSpecificationImpl(this.getIndex(), this.getCondition().negate(), this.getSearchValue(), this.getMatchMode()); } @Override protected Class<String> getElementValueClass() { return String.class; } @Override public SearchSpecification<String, String> onIndex(final SecondaryIndex index) { Preconditions.checkArgument( Objects.equals(index.getName(), this.index.getName()), "Cannot move search specification on the given index - the index names do not match!" ); return new StringSearchSpecificationImpl(index, this.condition, this.searchValue, this.matchMode); } // ================================================================================================================= // HASH CODE & EQUALS // ================================================================================================================= @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; StringSearchSpecificationImpl that = (StringSearchSpecificationImpl) o; return matchMode == that.matchMode; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (matchMode != null ? matchMode.hashCode() : 0); return result; } @Override public String toString() { return this.getIndex() + " " + this.getCondition().getInfix() + " " + this.getMatchMode() + " '" + this.getSearchValue() + "'"; } }
3,697
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AbstractSearchSpecification.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/AbstractSearchSpecification.java
package org.chronos.chronodb.internal.impl.query; import static com.google.common.base.Preconditions.*; import com.google.common.primitives.Primitives; import org.chronos.chronodb.api.SecondaryIndex; import org.chronos.chronodb.api.exceptions.InvalidIndexAccessException; import org.chronos.chronodb.api.query.Condition; import org.chronos.chronodb.internal.api.query.searchspec.SearchSpecification; public abstract class AbstractSearchSpecification<ELEMENTVALUE, CONDITIONTYPE extends Condition, SEARCHVALUE> implements SearchSpecification<ELEMENTVALUE, SEARCHVALUE> { protected final SecondaryIndex index; protected final CONDITIONTYPE condition; protected final SEARCHVALUE searchValue; protected AbstractSearchSpecification(final SecondaryIndex index, final CONDITIONTYPE condition, final SEARCHVALUE searchValue) { checkNotNull(index, "Precondition violation - argument 'index' must not be NULL!"); checkNotNull(condition, "Precondition violation - argument 'condition' must not be NULL!"); checkNotNull(searchValue, "Precondition violation - argument 'searchValue' must not be NULL!"); this.checkIndexType(index); this.index = index; this.condition = condition; this.searchValue = searchValue; } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public SecondaryIndex getIndex(){ return this.index; } @Override public SEARCHVALUE getSearchValue() { return this.searchValue; } @Override public CONDITIONTYPE getCondition() { return this.condition; } // ================================================================================================================= // HASH CODE & EQUALS // ================================================================================================================= @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.condition == null ? 0 : this.condition.hashCode()); result = prime * result + (this.index == null ? 0 : this.index.hashCode()); result = prime * result + (this.searchValue == null ? 0 : this.searchValue.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; } AbstractSearchSpecification<?, ?, ?> other = (AbstractSearchSpecification<?, ?, ?>) obj; if (this.condition == null) { if (other.condition != null) { return false; } } else if (!this.condition.equals(other.condition)) { return false; } if (this.index == null) { if (other.index != null) { return false; } } else if (!this.index.equals(other.index)) { return false; } if (this.searchValue == null) { if (other.searchValue != null) { return false; } } else if (!this.searchValue.equals(other.searchValue)) { return false; } return true; } @Override public String toString() { return this.getIndex() + " " + this.getCondition().getInfix() + " '" + this.getSearchValue() + "'"; } protected abstract Class<ELEMENTVALUE> getElementValueClass(); private void checkIndexType(SecondaryIndex index){ Class<ELEMENTVALUE> expectedValueType = Primitives.wrap(this.getElementValueClass()); Class<?> indexValueType = Primitives.wrap(index.getValueType()); if (!expectedValueType.equals(indexValueType)) { throw new InvalidIndexAccessException( "Cannot create search specification of type '" + expectedValueType.getSimpleName() + "' on index of type '" + indexValueType.getSimpleName() + "'!" ); } } }
3,823
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ContainmentStringSearchSpecificationImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/ContainmentStringSearchSpecificationImpl.java
package org.chronos.chronodb.internal.impl.query; import com.google.common.base.Preconditions; import org.chronos.chronodb.api.SecondaryIndex; import org.chronos.chronodb.api.query.DoubleContainmentCondition; import org.chronos.chronodb.api.query.StringContainmentCondition; import org.chronos.chronodb.internal.api.query.searchspec.ContainmentDoubleSearchSpecification; import org.chronos.chronodb.internal.api.query.searchspec.ContainmentStringSearchSpecification; import org.chronos.chronodb.internal.api.query.searchspec.SearchSpecification; import java.util.Objects; import java.util.Set; import java.util.function.Predicate; import static com.google.common.base.Preconditions.*; public class ContainmentStringSearchSpecificationImpl extends AbstractSearchSpecification<String, StringContainmentCondition, Set<String>> implements ContainmentStringSearchSpecification { // ================================================================================================================= // FIELDS // ================================================================================================================= private final TextMatchMode matchMode; // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= public ContainmentStringSearchSpecificationImpl(final SecondaryIndex index, final StringContainmentCondition condition, final Set<String> searchValue, TextMatchMode matchMode) { super(index, condition, searchValue); checkNotNull(matchMode, "Precondition violation - argument 'matchMode' must not be NULL!"); this.matchMode = matchMode; } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public TextMatchMode getMatchMode() { return this.matchMode; } @Override public Predicate<Object> toFilterPredicate() { return obj -> { if (obj instanceof String == false) { return false; } String value = (String) obj; return this.condition.applies(value, this.searchValue, this.matchMode); }; } @Override protected Class<String> getElementValueClass() { return String.class; } @Override public SearchSpecification<String, Set<String>> negate() { return new ContainmentStringSearchSpecificationImpl(this.getIndex(), this.condition.negate(), this.searchValue, this.matchMode); } @Override public SearchSpecification<String, Set<String>> onIndex(final SecondaryIndex index) { Preconditions.checkArgument( Objects.equals(index.getName(), this.index.getName()), "Cannot move search specification on the given index - the index names do not match!" ); return new ContainmentStringSearchSpecificationImpl(index, this.condition, this.searchValue, this.matchMode); } // ================================================================================================================= // HASH CODE, EQUALS, TOSTRING // ================================================================================================================= @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; ContainmentStringSearchSpecificationImpl that = (ContainmentStringSearchSpecificationImpl) o; return matchMode == that.matchMode; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (matchMode != null ? matchMode.hashCode() : 0); return result; } @Override public String toString() { return this.getIndex() + " " + this.getCondition().getInfix() + " " + this.getMatchMode() + " '" + this.getSearchValue() + "'"; } }
4,314
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
StandardQueryParser.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/parser/StandardQueryParser.java
package org.chronos.chronodb.internal.impl.query.parser; import static com.google.common.base.Preconditions.*; import org.chronos.chronodb.api.exceptions.ChronoDBQuerySyntaxException; import org.chronos.chronodb.api.query.*; import org.chronos.chronodb.internal.api.query.ChronoDBQuery; import org.chronos.chronodb.internal.api.query.QueryParser; import org.chronos.chronodb.internal.api.query.QueryTokenStream; import org.chronos.chronodb.internal.impl.builder.query.StandardQueryTokenStream; import org.chronos.chronodb.internal.impl.query.TextMatchMode; import org.chronos.chronodb.internal.impl.query.parser.ast.*; import org.chronos.chronodb.internal.impl.query.parser.token.AndToken; import org.chronos.chronodb.internal.impl.query.parser.token.BeginToken; import org.chronos.chronodb.internal.impl.query.parser.token.EndOfInputToken; import org.chronos.chronodb.internal.impl.query.parser.token.EndToken; import org.chronos.chronodb.internal.impl.query.parser.token.KeyspaceToken; import org.chronos.chronodb.internal.impl.query.parser.token.NotToken; import org.chronos.chronodb.internal.impl.query.parser.token.OrToken; import org.chronos.chronodb.internal.impl.query.parser.token.QueryToken; import org.chronos.chronodb.internal.impl.query.parser.token.WhereToken; import org.chronos.chronodb.internal.impl.query.parser.token.WhereToken.*; import java.util.Set; /** * This is the parser for the ChronoDB query language. * * <p> * This class operates on a {@link StandardQueryTokenStream} that is passed to * the constructor. Instances of this class can be created as needed by using * that constructor. * * <p> * The grammar of this language is as follows:<br> * <br> * * <pre> * query : KEYSPACE expression EOI * * expression : term * | term OR term * * term : factor * | factor AND factor * * factor : BEGIN exp END * | WHERE * | NOT factor * * </pre> * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API */ public class StandardQueryParser implements QueryParser { /** * Parses the {@link ChronoDBQuery} from the given {@link QueryTokenStream}. * * <p> * Please note that this method may be called only once per instance. * * @param tokenStream The token stream to parse. Must not be <code>null</code>. Must * not be in use by another parser. * @return The parsed query. Never <code>null</code>. * @throws ChronoDBQuerySyntaxException Thrown if a parse error occurs. * @throws IllegalStateException Thrown if this method was already called on this instance. */ @Override public ChronoDBQuery parse(final QueryTokenStream tokenStream) throws ChronoDBQuerySyntaxException { checkNotNull(tokenStream, "Precondition violation - argument 'tokenStream' must not be NULL!"); checkArgument(tokenStream.isAtStartOfInput(), "Precondition violation - argument 'tokenStream' is in use by another parser!"); return this.parseQuery(tokenStream); } /** * Parses the root-level <i>query</i> in the query language from the token * stream. * * <p> * The corresponding grammar rule is:<br> * <br> * * <pre> * query : KEYSPACE expression EOI * </pre> * * @param tokenStream The token stream to parse. Must not be <code>null</code>. Must * not be in use by another parser. * @return The parsed AST element. Never <code>null</code>. * @throws ChronoDBQuerySyntaxException Thrown if a parse error occurs. */ private ChronoDBQuery parseQuery(final QueryTokenStream tokenStream) { KeyspaceToken token = this.match(tokenStream, KeyspaceToken.class); if (token == null) { throw new ChronoDBQuerySyntaxException("Missing keyspace declaration at start of query!"); } String keyspace = token.getKeyspace(); QueryElement element = this.parseExpression(tokenStream); EndOfInputToken eoiToken = this.match(tokenStream, EndOfInputToken.class); if (eoiToken == null) { this.throwParseErrorExpected(tokenStream, "End Of Input"); } ChronoDBQueryImpl query = new ChronoDBQueryImpl(keyspace, element); return query; } /** * Parses an <i>expression</i> in the query language from the token stream. * * <p> * The corresponding grammar rule is:<br> * <br> * * <pre> * expression : term * | term OR expression * </pre> * * @param tokenStream The token stream to parse. Must not be <code>null</code>. Must * not be in use by another parser. * @return The parsed AST element. Never <code>null</code>. * @throws ChronoDBQuerySyntaxException Thrown if a parse error occurs. */ private QueryElement parseExpression(final QueryTokenStream tokenStream) throws ChronoDBQuerySyntaxException { QueryElement term = this.parseTerm(tokenStream); // check if the next token is an OR OrToken orToken = this.match(tokenStream, OrToken.class); if (orToken != null) { // we have the OR case, parse the second term QueryElement secondTerm = this.parseExpression(tokenStream); // construct the binary operation Element QueryElement orOpElement = new BinaryOperatorElement(term, BinaryQueryOperator.OR, secondTerm); return orOpElement; } else { // we have the simple case where an expression is just a single term, return it return term; } } /** * Parses a <i>term</i> in the query language from the token stream. * * <p> * The corresponding grammar rule is:<br> * <br> * * <pre> * term : factor * | factor AND term * </pre> * * @param tokenStream The token stream to parse. Must not be <code>null</code>. Must * not be in use by another parser. * @return The parsed AST element. Never <code>null</code>. * @throws ChronoDBQuerySyntaxException Thrown if a parse error occurs. */ private QueryElement parseTerm(final QueryTokenStream tokenStream) throws ChronoDBQuerySyntaxException { QueryElement factor = this.parseFactor(tokenStream); // check if the next token is an AND AndToken andToken = this.match(tokenStream, AndToken.class); if (andToken != null) { // we have the AND case, parse the second term QueryElement secondFactor = this.parseTerm(tokenStream); // construct the binary operation element QueryElement andOpElement = new BinaryOperatorElement(factor, BinaryQueryOperator.AND, secondFactor); return andOpElement; } else { // we have the simple case where a term is just a single factor, return it return factor; } } /** * Parses a <i>factor</i> in the query language from the token stream. * * <p> * The corresponding grammar rule is:<br> * <br> * * <pre> * factor : BEGIN exp END * | WHERE * | NOT factor * </pre> * * @param tokenStream The token stream to parse. Must not be <code>null</code>. Must * not be in use by another parser. * @return The parsed AST element. Never <code>null</code>. * @throws ChronoDBQuerySyntaxException Thrown if a parse error occurs. */ private QueryElement parseFactor(final QueryTokenStream tokenStream) throws ChronoDBQuerySyntaxException { BeginToken beginToken = this.match(tokenStream, BeginToken.class); if (beginToken != null) { // match the contained expression QueryElement expression = this.parseExpression(tokenStream); // match the END EndToken endToken = this.match(tokenStream, EndToken.class); if (endToken == null) { this.throwParseErrorExpected(tokenStream, "end"); } // return the contained expression (as factor) return expression; } WhereToken whereToken = this.match(tokenStream, WhereToken.class); if (whereToken != null) { // construct the AST element for the WHERE clause and return it (as factor) if (whereToken.isStringWhereToken()) { StringWhereDetails stringWhereToken = whereToken.asStringWhereToken(); String indexName = stringWhereToken.getIndexName(); StringCondition condition = stringWhereToken.getCondition(); TextMatchMode matchMode = stringWhereToken.getMatchMode(); String comparisonValue = stringWhereToken.getComparisonValue(); QueryElement whereElement = new StringWhereElement(indexName, condition, matchMode, comparisonValue); return whereElement; } else if (whereToken.isLongWhereToken()) { LongWhereDetails longWhereToken = whereToken.asLongWhereToken(); String indexName = longWhereToken.getIndexName(); NumberCondition condition = longWhereToken.getCondition(); long comparisonValue = longWhereToken.getComparisonValue(); QueryElement whereElement = new LongWhereElement(indexName, condition, comparisonValue); return whereElement; } else if (whereToken.isDoubleWhereToken()) { DoubleWhereDetails doubleWhereToken = whereToken.asDoubleWhereToken(); String indexName = doubleWhereToken.getIndexName(); NumberCondition condition = doubleWhereToken.getCondition(); double comparisonValue = doubleWhereToken.getComparisonValue(); double equalityTolerance = doubleWhereToken.getEqualityTolerance(); QueryElement whereElement = new DoubleWhereElement(indexName, condition, comparisonValue, equalityTolerance); return whereElement; } else if (whereToken.isSetStringWhereToken()) { SetStringWhereDetails setStringWhereToken = whereToken.asSetStringWhereToken(); String indexName = setStringWhereToken.getIndexName(); StringContainmentCondition condition = setStringWhereToken.getCondition(); TextMatchMode matchMode = setStringWhereToken.getMatchMode(); Set<String> comparisonValues = setStringWhereToken.getComparisonValue(); QueryElement whereElement = new SetStringWhereElement(indexName, condition, matchMode, comparisonValues); return whereElement; } else if (whereToken.isSetLongWhereToken()) { SetLongWhereDetails setLongWhereToken = whereToken.asSetLongWhereToken(); String indexName = setLongWhereToken.getIndexName(); LongContainmentCondition condition = setLongWhereToken.getCondition(); Set<Long> comparisonValues = setLongWhereToken.getComparisonValue(); QueryElement whereElement = new SetLongWhereElement(indexName, condition, comparisonValues); return whereElement; } else if(whereToken.isSetDoubleWhereToken()){ SetDoubleWhereDetails setDoubleWhereToken = whereToken.asSetDoubleWhereToken(); String indexName = setDoubleWhereToken.getIndexName(); DoubleContainmentCondition condition = setDoubleWhereToken.getCondition(); Set<Double> comparisonValues = setDoubleWhereToken.getComparisonValue(); double equalityTolerance = setDoubleWhereToken.getEqualityTolerance(); QueryElement whereElement = new SetDoubleWhereElement(indexName, condition, comparisonValues, equalityTolerance); return whereElement; } else { throw new IllegalStateException("Unknown details on Where token!"); } } NotToken notToken = this.match(tokenStream, NotToken.class); if (notToken != null) { // parse the inner factor QueryElement factor = this.parseFactor(tokenStream); // wrap the factor in the NOT element QueryElement notElement = new NotElement(factor); return notElement; } // otherwise, we have a parse error... this.throwParseErrorExpected(tokenStream, "begin", "where", "not"); // this code is actually unreachable, it's here to satisfy the compiler return null; } /** * Attempts to match the next token in the stream with the given token * class. * * <p> * If the next token in the stream is an instance of the given expected * token class, the token is consumed from the stream and returned. * Otherwise, the token remains in the stream and this method returns * <code>null</code>. * * @param <T> The expected type of token which should come next in the * stream. * @param tokenStream The token stream to parse. Must not be <code>null</code>. Must * not be in use by another parser. * @param expectedTokenClass The expected type of token. Must not be <code>null</code>. * @return The next token in the stream, which also matches the given class, * or <code>null</code> if the next token in the stream does not * match the class. */ @SuppressWarnings("unchecked") private < T extends QueryToken> T match( final QueryTokenStream tokenStream, final Class<T> expectedTokenClass) { checkNotNull(expectedTokenClass, "Precondition violation - argument 'expectedTokenClass' must not be NULL!"); if (tokenStream.hasNextToken() == false) { // well, there is nothing to match against... return null; } QueryToken token = tokenStream.lookAhead(); if (expectedTokenClass.isInstance(token)) { tokenStream.getToken(); return (T) token; } return null; } /** * Throws a {@link ChronoDBQuerySyntaxException} with the given message. * * @param message The message for the exception. Must not be <code>null</code>. */ private void throwParseError ( final String message) { checkNotNull(message, "Precondition violation - argument 'message' must not be NULL!"); throw new ChronoDBQuerySyntaxException("Parse Error: " + message); } /** * Throws a {@link ChronoDBQuerySyntaxException} stating that the given * sequence of tokens was expected, but the next token in the stream was * found. * * @param tokenStream The token stream to parse. Must not be <code>null</code>. Must * not be in use by another parser. * @param expected The expected token types. Must not be <code>null</code>. */ private void throwParseErrorExpected ( final QueryTokenStream tokenStream, final String... expected) { StringBuilder builder = new StringBuilder(); builder.append("Expected { "); String separator = ""; for (String expectedToken : expected) { builder.append(separator); separator = ", "; builder.append(expectedToken); } builder.append(" }, "); if (tokenStream.hasNextToken()) { builder.append("but found '" + tokenStream.lookAhead() + "'!"); } else { builder.append("but the token stream has no more tokens!"); } this.throwParseError(builder.toString()); } }
15,816
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
DoubleWhereElement.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/parser/ast/DoubleWhereElement.java
package org.chronos.chronodb.internal.impl.query.parser.ast; import static com.google.common.base.Preconditions.*; import com.google.common.collect.Sets; import org.chronos.chronodb.api.SecondaryIndex; import org.chronos.chronodb.api.query.*; import org.chronos.chronodb.internal.api.query.searchspec.DoubleSearchSpecification; import org.chronos.chronodb.internal.api.query.searchspec.SearchSpecification; import java.util.Objects; import java.util.Set; public class DoubleWhereElement extends WhereElement<Double, NumberCondition> { private final double equalityTolerance; public DoubleWhereElement(final String indexName, final NumberCondition condition, final double comparisonValue, final double equalityTolerance) { super(indexName, condition, comparisonValue); checkArgument(equalityTolerance >= 0, "Precondition violation - argument 'equalityTolerance' must not be negative!"); this.equalityTolerance = equalityTolerance; } public double getEqualityTolerance() { return this.equalityTolerance; } @Override public DoubleWhereElement negate() { return new DoubleWhereElement(this.getIndexName(), this.getCondition().negate(), this.getComparisonValue(), this.getEqualityTolerance()); } @Override public SearchSpecification<?, ?> toSearchSpecification(SecondaryIndex index) { if(!Objects.equals(index.getName(), this.indexName)){ throw new IllegalArgumentException("Cannot use index '" + index.getName() + "' for search specification - expected index name is '" + this.indexName + "'!"); } return DoubleSearchSpecification.create(index, this.getCondition(), this.getComparisonValue(), this.getEqualityTolerance()); } @Override public WhereElement<Set<Double>, DoubleContainmentCondition> collapseToInClause(final WhereElement<?, ?> other) { if (!this.indexName.equals(other.getIndexName())) { // cannot mix queries on different properties (e.g. firstname and lastname) return null; } if (this.condition.equals(NumberCondition.EQUALS)) { if (other instanceof DoubleWhereElement) { DoubleWhereElement otherDoubleWhere = (DoubleWhereElement) other; if (otherDoubleWhere.getCondition().equals(NumberCondition.EQUALS) && this.equalityTolerance == otherDoubleWhere.getEqualityTolerance()) { return new SetDoubleWhereElement(this.indexName, DoubleContainmentCondition.WITHIN, Sets.newHashSet(this.comparisonValue, otherDoubleWhere.getComparisonValue()), this.equalityTolerance); } } else if (other instanceof SetDoubleWhereElement) { SetDoubleWhereElement otherSetStringWhere = (SetDoubleWhereElement) other; if (otherSetStringWhere.getCondition().equals(DoubleContainmentCondition.WITHIN) && this.equalityTolerance == otherSetStringWhere.getEqualityTolerance()) { Set<Double> inClause = Sets.newHashSet(otherSetStringWhere.getComparisonValue()); inClause.add(this.comparisonValue); return new SetDoubleWhereElement(this.indexName, DoubleContainmentCondition.WITHIN, inClause, this.equalityTolerance); } } } else if (this.condition.equals(NumberCondition.NOT_EQUALS)) { if (other instanceof DoubleWhereElement) { DoubleWhereElement otherDoubleWhere = (DoubleWhereElement) other; if (otherDoubleWhere.getCondition().equals(NumberCondition.NOT_EQUALS) && this.equalityTolerance == otherDoubleWhere.getEqualityTolerance()) { return new SetDoubleWhereElement(this.indexName, DoubleContainmentCondition.WITHOUT, Sets.newHashSet(this.comparisonValue, otherDoubleWhere.getComparisonValue()), this.equalityTolerance); } } else if (other instanceof SetDoubleWhereElement) { SetDoubleWhereElement otherSetDoubleWhere = (SetDoubleWhereElement) other; if (otherSetDoubleWhere.getCondition().equals(DoubleContainmentCondition.WITHOUT) && this.equalityTolerance == otherSetDoubleWhere.getEqualityTolerance()) { Set<Double> inClause = Sets.newHashSet(otherSetDoubleWhere.getComparisonValue()); inClause.add(this.comparisonValue); return new SetDoubleWhereElement(this.indexName, DoubleContainmentCondition.WITHOUT, inClause, this.equalityTolerance); } } } return null; } }
4,124
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoDBQueryImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/parser/ast/ChronoDBQueryImpl.java
package org.chronos.chronodb.internal.impl.query.parser.ast; import org.chronos.chronodb.internal.api.query.ChronoDBQuery; public class ChronoDBQueryImpl implements ChronoDBQuery { private final String keyspace; private final QueryElement rootElement; public ChronoDBQueryImpl(final String keyspace, final QueryElement element) { this.keyspace = keyspace; this.rootElement = element; } @Override public String getKeyspace() { return this.keyspace; } @Override public QueryElement getRootElement() { return this.rootElement; } @Override public String toString() { return "Query[keyspace='" + this.keyspace + "', AST=" + this.rootElement + "]"; } }
678
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
QueryElement.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/parser/ast/QueryElement.java
package org.chronos.chronodb.internal.impl.query.parser.ast; import org.chronos.chronodb.internal.api.query.ChronoDBQuery; /** * A {@link QueryElement} represents a single element in the Abstract Syntax Tree (AST) of a {@link ChronoDBQuery}. * * <p> * Please note that all instances of classes that implement this interface are assumed to be <code>immutable</code>. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public interface QueryElement { }
487
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
NotElement.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/parser/ast/NotElement.java
package org.chronos.chronodb.internal.impl.query.parser.ast; public class NotElement implements QueryElement { private final QueryElement child; // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= public NotElement(final QueryElement childExpression) { this.child = childExpression; } // ================================================================================================================= // PUBLIC API // ================================================================================================================= public QueryElement getChild() { return this.child; } // ================================================================================================================= // TO STRING // ================================================================================================================= @Override public String toString() { return "not(" + this.child + ")"; } }
1,137
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
LongWhereElement.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/parser/ast/LongWhereElement.java
package org.chronos.chronodb.internal.impl.query.parser.ast; import com.google.common.collect.Sets; import org.chronos.chronodb.api.SecondaryIndex; import org.chronos.chronodb.api.query.ContainmentCondition; import org.chronos.chronodb.api.query.LongContainmentCondition; import org.chronos.chronodb.api.query.NumberCondition; import org.chronos.chronodb.internal.api.query.searchspec.LongSearchSpecification; import org.chronos.chronodb.internal.api.query.searchspec.SearchSpecification; import java.util.Objects; import java.util.Set; public class LongWhereElement extends WhereElement<Long, NumberCondition> { public LongWhereElement(final String indexName, final NumberCondition condition, final Long comparisonValue) { super(indexName, condition, comparisonValue); } @Override public LongWhereElement negate() { return new LongWhereElement(this.getIndexName(), this.getCondition().negate(), this.getComparisonValue()); } @Override public SearchSpecification<?, ?> toSearchSpecification(SecondaryIndex index) { if(!Objects.equals(index.getName(), this.indexName)){ throw new IllegalArgumentException("Cannot use index '" + index.getName() + "' for search specification - expected index name is '" + this.indexName + "'!"); } return LongSearchSpecification.create(index, this.getCondition(), this.getComparisonValue()); } @Override public WhereElement<Set<Long>, LongContainmentCondition> collapseToInClause(final WhereElement<?, ?> other) { if (!this.indexName.equals(other.getIndexName())) { // cannot mix queries on different properties (e.g. firstname and lastname) return null; } if (this.condition.equals(NumberCondition.EQUALS)) { if (other instanceof LongWhereElement) { LongWhereElement otherLongWhere = (LongWhereElement) other; if (otherLongWhere.getCondition().equals(NumberCondition.EQUALS)) { return new SetLongWhereElement(this.indexName, LongContainmentCondition.WITHIN, Sets.newHashSet(this.comparisonValue, otherLongWhere.getComparisonValue())); } } else if (other instanceof SetLongWhereElement) { SetLongWhereElement otherSetLongWhere = (SetLongWhereElement) other; if (otherSetLongWhere.getCondition().equals(LongContainmentCondition.WITHIN)) { Set<Long> inClause = Sets.newHashSet(otherSetLongWhere.getComparisonValue()); inClause.add(this.comparisonValue); return new SetLongWhereElement(this.indexName, LongContainmentCondition.WITHIN, inClause); } } } else if (this.condition.equals(NumberCondition.NOT_EQUALS)) { if (other instanceof LongWhereElement) { LongWhereElement otherLongWhere = (LongWhereElement) other; if (otherLongWhere.getCondition().equals(NumberCondition.NOT_EQUALS)) { return new SetLongWhereElement(this.indexName, LongContainmentCondition.WITHOUT, Sets.newHashSet(this.comparisonValue, otherLongWhere.getComparisonValue())); } } else if (other instanceof SetLongWhereElement) { SetLongWhereElement otherSetLongWhere = (SetLongWhereElement) other; if (otherSetLongWhere.getCondition().equals(LongContainmentCondition.WITHOUT)) { Set<Long> inClause = Sets.newHashSet(otherSetLongWhere.getComparisonValue()); inClause.add(this.comparisonValue); return new SetLongWhereElement(this.indexName, LongContainmentCondition.WITHOUT, inClause); } } } // in any other case, we cannot collapse return null; } }
3,835
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
StringWhereElement.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/parser/ast/StringWhereElement.java
package org.chronos.chronodb.internal.impl.query.parser.ast; import static com.google.common.base.Preconditions.*; import com.google.common.collect.Sets; import org.chronos.chronodb.api.SecondaryIndex; import org.chronos.chronodb.api.query.*; import org.chronos.chronodb.internal.api.query.searchspec.SearchSpecification; import org.chronos.chronodb.internal.api.query.searchspec.StringSearchSpecification; import org.chronos.chronodb.internal.impl.query.TextMatchMode; import java.util.Objects; import java.util.Set; public class StringWhereElement extends WhereElement<String, StringCondition> { protected final TextMatchMode matchMode; public StringWhereElement(final String indexName, final StringCondition condition, final TextMatchMode matchMode, final String comparisonValue) { super(indexName, condition, comparisonValue); checkNotNull(matchMode, "Precondition violation - argument 'matchMode' must not be NULL!"); this.matchMode = matchMode; } public TextMatchMode getMatchMode() { return this.matchMode; } @Override public StringWhereElement negate() { return new StringWhereElement(this.getIndexName(), this.getCondition().negate(), this.getMatchMode(), this.getComparisonValue()); } @Override public SearchSpecification<?, ?> toSearchSpecification(SecondaryIndex index) { if(!Objects.equals(index.getName(), this.indexName)){ throw new IllegalArgumentException("Cannot use index '" + index.getName() + "' for search specification - expected index name is '" + this.indexName + "'!"); } return StringSearchSpecification.create(index, this.getCondition(), this.getMatchMode(), this.getComparisonValue()); } @Override public WhereElement<Set<String>, StringContainmentCondition> collapseToInClause(final WhereElement<?, ?> other) { if (!this.indexName.equals(other.getIndexName())) { // cannot mix queries on different properties (e.g. firstname and lastname) return null; } if (this.condition.equals(StringCondition.EQUALS)) { if (other instanceof StringWhereElement) { StringWhereElement otherStringWhere = (StringWhereElement) other; if (otherStringWhere.getCondition().equals(StringCondition.EQUALS) && this.matchMode.equals(otherStringWhere.getMatchMode())) { return new SetStringWhereElement(this.indexName, StringContainmentCondition.WITHIN, this.matchMode, Sets.newHashSet(this.comparisonValue, otherStringWhere.getComparisonValue())); } } else if (other instanceof SetStringWhereElement) { SetStringWhereElement otherSetStringWhere = (SetStringWhereElement) other; if (otherSetStringWhere.getCondition().equals(StringContainmentCondition.WITHIN) && this.matchMode.equals(otherSetStringWhere.getMatchMode())) { Set<String> inClause = Sets.newHashSet(otherSetStringWhere.getComparisonValue()); inClause.add(this.comparisonValue); return new SetStringWhereElement(this.indexName, StringContainmentCondition.WITHIN, this.matchMode, inClause); } } } else if (this.condition.equals(StringCondition.NOT_EQUALS)) { if (other instanceof StringWhereElement) { StringWhereElement otherStringWhere = (StringWhereElement) other; if (otherStringWhere.getCondition().equals(StringCondition.NOT_EQUALS) && this.matchMode.equals(otherStringWhere.getMatchMode())) { return new SetStringWhereElement(this.indexName, StringContainmentCondition.WITHOUT, this.matchMode, Sets.newHashSet(this.comparisonValue, otherStringWhere.getComparisonValue())); } } else if (other instanceof SetStringWhereElement) { SetStringWhereElement otherSetStringWhere = (SetStringWhereElement) other; if (otherSetStringWhere.getCondition().equals(StringContainmentCondition.WITHOUT) && this.matchMode.equals(otherSetStringWhere.getMatchMode())) { Set<String> inClause = Sets.newHashSet(otherSetStringWhere.getComparisonValue()); inClause.add(this.comparisonValue); return new SetStringWhereElement(this.indexName, StringContainmentCondition.WITHOUT, this.matchMode, inClause); } } } return null; } }
4,514
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
BinaryOperatorElement.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/parser/ast/BinaryOperatorElement.java
package org.chronos.chronodb.internal.impl.query.parser.ast; import static com.google.common.base.Preconditions.*; public class BinaryOperatorElement implements QueryElement { // ================================================================================================================= // PROPERTIES // ================================================================================================================= private final BinaryQueryOperator operator; private final QueryElement leftChild; private final QueryElement rightChild; // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= public BinaryOperatorElement(final QueryElement left, final BinaryQueryOperator operator, final QueryElement right) { checkNotNull(left, "Precondition violation - argument 'left' must not be NULL!"); checkNotNull(operator, "Precondition violation - argument 'operator' must not be NULL!"); checkNotNull(right, "Precondition violation - argument 'right' must not be NULL!"); this.leftChild = left; this.rightChild = right; this.operator = operator; } // ================================================================================================================= // GETTERS & SETTERS // ================================================================================================================= public BinaryQueryOperator getOperator() { return this.operator; } public QueryElement getLeftChild() { return this.leftChild; } public QueryElement getRightChild() { return this.rightChild; } // ================================================================================================================= // TO STRING // ================================================================================================================= @Override public String toString() { return "(" + this.leftChild + ") " + this.operator + " (" + this.rightChild + ")"; } }
2,125
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
SetStringWhereElement.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/parser/ast/SetStringWhereElement.java
package org.chronos.chronodb.internal.impl.query.parser.ast; import com.google.common.collect.Sets; import org.chronos.chronodb.api.SecondaryIndex; import org.chronos.chronodb.api.query.ContainmentCondition; import org.chronos.chronodb.api.query.LongContainmentCondition; import org.chronos.chronodb.api.query.StringContainmentCondition; import org.chronos.chronodb.internal.api.query.searchspec.ContainmentStringSearchSpecification; import org.chronos.chronodb.internal.api.query.searchspec.SearchSpecification; import org.chronos.chronodb.internal.impl.query.TextMatchMode; import java.util.Objects; import java.util.Set; import static com.google.common.base.Preconditions.*; public class SetStringWhereElement extends WhereElement<Set<String>, StringContainmentCondition> { private final TextMatchMode matchMode; public SetStringWhereElement(final String indexName, StringContainmentCondition condition, TextMatchMode matchMode, Set<String> comparisonValues){ super(indexName, condition, comparisonValues); checkNotNull(matchMode, "Precondition violation - argument 'matchMode' must not be NULL!"); this.matchMode = matchMode; } @Override public SetStringWhereElement negate() { return new SetStringWhereElement(this.indexName, this.condition.negate(), this.matchMode, this.comparisonValue); } @Override public SearchSpecification<?, ?> toSearchSpecification(SecondaryIndex index) { if(!Objects.equals(index.getName(), this.indexName)){ throw new IllegalArgumentException("Cannot use index '" + index.getName() + "' for search specification - expected index name is '" + this.indexName + "'!"); } return ContainmentStringSearchSpecification.create(index, this.getCondition(), this.matchMode, this.getComparisonValue()); } public TextMatchMode getMatchMode() { return this.matchMode; } @Override public WhereElement<Set<String>, StringContainmentCondition> collapseToInClause(final WhereElement<?, ?> other) { if (!this.indexName.equals(other.getIndexName())) { // cannot mix queries on different properties (e.g. firstname and lastname) return null; } if (this.condition.equals(StringContainmentCondition.WITHIN)) { if (other instanceof StringWhereElement) { StringWhereElement otherStringWhere = (StringWhereElement) other; return otherStringWhere.collapseToInClause(this); } else if (other instanceof SetStringWhereElement) { SetStringWhereElement otherSetStringWhere = (SetStringWhereElement) other; if (otherSetStringWhere.getCondition().equals(StringContainmentCondition.WITHIN) && this.matchMode.equals(otherSetStringWhere.getMatchMode())) { Set<String> inClause = Sets.newHashSet(otherSetStringWhere.getComparisonValue()); inClause.addAll(this.comparisonValue); return new SetStringWhereElement(this.indexName, StringContainmentCondition.WITHIN, this.matchMode, inClause); } } } else if (this.condition.equals(StringContainmentCondition.WITHOUT)) { if (other instanceof StringWhereElement) { StringWhereElement otherLongWhere = (StringWhereElement) other; return otherLongWhere.collapseToInClause(this); } else if (other instanceof SetStringWhereElement) { SetStringWhereElement otherSetStringWhere = (SetStringWhereElement) other; if (otherSetStringWhere.getCondition().equals(StringContainmentCondition.WITHOUT) && this.matchMode.equals(otherSetStringWhere.getMatchMode())) { Set<String> inClause = Sets.newHashSet(otherSetStringWhere.getComparisonValue()); inClause.addAll(this.comparisonValue); return new SetStringWhereElement(this.indexName, StringContainmentCondition.WITHOUT, this.matchMode, inClause); } } } return null; } }
4,113
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
SetDoubleWhereElement.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/parser/ast/SetDoubleWhereElement.java
package org.chronos.chronodb.internal.impl.query.parser.ast; import com.google.common.collect.Sets; import org.chronos.chronodb.api.SecondaryIndex; import org.chronos.chronodb.api.query.ContainmentCondition; import org.chronos.chronodb.api.query.DoubleContainmentCondition; import org.chronos.chronodb.api.query.StringContainmentCondition; import org.chronos.chronodb.internal.api.query.searchspec.ContainmentDoubleSearchSpecification; import org.chronos.chronodb.internal.api.query.searchspec.SearchSpecification; import java.util.Objects; import java.util.Set; public class SetDoubleWhereElement extends WhereElement<Set<Double>, DoubleContainmentCondition> { private final double equalityTolerance; public SetDoubleWhereElement(final String indexName, DoubleContainmentCondition condition, Set<Double> comparisonValues, double equalityTolerance) { super(indexName, condition, comparisonValues); this.equalityTolerance = equalityTolerance; } @Override public SetDoubleWhereElement negate() { return new SetDoubleWhereElement(this.indexName, this.condition.negate(), this.comparisonValue, this.equalityTolerance); } @Override public SearchSpecification<?, ?> toSearchSpecification(SecondaryIndex index) { if(!Objects.equals(index.getName(), this.indexName)){ throw new IllegalArgumentException("Cannot use index '" + index.getName() + "' for search specification - expected index name is '" + this.indexName + "'!"); } return ContainmentDoubleSearchSpecification.create(index, this.getCondition(), this.getComparisonValue(), this.equalityTolerance); } public double getEqualityTolerance() { return equalityTolerance; } @Override public WhereElement<Set<Double>, DoubleContainmentCondition> collapseToInClause(final WhereElement<?, ?> other) { if (!this.indexName.equals(other.getIndexName())) { // cannot mix queries on different properties (e.g. firstname and lastname) return null; } if (this.condition.equals(DoubleContainmentCondition.WITHIN)) { if (other instanceof DoubleWhereElement) { DoubleWhereElement otherDoubleWhere = (DoubleWhereElement) other; return otherDoubleWhere.collapseToInClause(this); } else if (other instanceof SetDoubleWhereElement) { SetDoubleWhereElement otherSetDoubleWhere = (SetDoubleWhereElement) other; if (otherSetDoubleWhere.getCondition().equals(DoubleContainmentCondition.WITHIN) && this.equalityTolerance == otherSetDoubleWhere.getEqualityTolerance()) { Set<Double> inClause = Sets.newHashSet(otherSetDoubleWhere.getComparisonValue()); inClause.addAll(this.comparisonValue); return new SetDoubleWhereElement(this.indexName, DoubleContainmentCondition.WITHIN, inClause, this.equalityTolerance); } } } else if (this.condition.equals(DoubleContainmentCondition.WITHOUT)) { if (other instanceof DoubleWhereElement) { DoubleWhereElement otherLongWhere = (DoubleWhereElement) other; return otherLongWhere.collapseToInClause(this); } else if (other instanceof SetDoubleWhereElement) { SetDoubleWhereElement otherSetDoubleWhere = (SetDoubleWhereElement) other; if (otherSetDoubleWhere.getCondition().equals(DoubleContainmentCondition.WITHOUT) && this.equalityTolerance == otherSetDoubleWhere.getEqualityTolerance()) { Set<Double> inClause = Sets.newHashSet(otherSetDoubleWhere.getComparisonValue()); inClause.addAll(this.comparisonValue); return new SetDoubleWhereElement(this.indexName, DoubleContainmentCondition.WITHOUT, inClause, this.equalityTolerance); } } } return null; } }
3,974
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
WhereElement.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/parser/ast/WhereElement.java
package org.chronos.chronodb.internal.impl.query.parser.ast; import static com.google.common.base.Preconditions.*; import org.chronos.chronodb.api.SecondaryIndex; import org.chronos.chronodb.api.query.Condition; import org.chronos.chronodb.api.query.ContainmentCondition; import org.chronos.chronodb.internal.api.query.searchspec.SearchSpecification; import org.chronos.chronodb.internal.impl.query.condition.string.ContainsCondition; import java.util.Set; public abstract class WhereElement<VALUETYPE, CONDITIONTYPE extends Condition> implements QueryElement { // ================================================================================================================= // PROPERTIES // ================================================================================================================= protected final CONDITIONTYPE condition; protected final String indexName; protected final VALUETYPE comparisonValue; // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= public WhereElement(final String indexName, final CONDITIONTYPE condition, final VALUETYPE comparisonValue) { checkNotNull(indexName, "Precondition violation - argument 'indexName' must not be NULL!"); checkNotNull(condition, "Precondition violation - argument 'condition' must not be NULL!"); checkNotNull(comparisonValue, "Precondition violation - argument 'comparisonValue' must not be NULL!"); this.indexName = indexName; this.condition = condition; this.comparisonValue = comparisonValue; } // ================================================================================================================= // public API // ================================================================================================================= public CONDITIONTYPE getCondition() { return this.condition; } public String getIndexName() { return this.indexName; } public VALUETYPE getComparisonValue() { return this.comparisonValue; } public abstract WhereElement<VALUETYPE, CONDITIONTYPE> negate(); public abstract SearchSpecification<?, ?> toSearchSpecification(SecondaryIndex index); public abstract WhereElement<?, ? extends ContainmentCondition> collapseToInClause(WhereElement<?,?> other); // ================================================================================================================= // TO STRING // ================================================================================================================= @Override public String toString() { return "where '" + this.indexName + "' " + this.condition.getInfix() + " '" + this.comparisonValue + "'"; } }
2,832
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
SetLongWhereElement.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/parser/ast/SetLongWhereElement.java
package org.chronos.chronodb.internal.impl.query.parser.ast; import com.google.common.collect.Sets; import org.chronos.chronodb.api.SecondaryIndex; import org.chronos.chronodb.api.query.ContainmentCondition; import org.chronos.chronodb.api.query.LongContainmentCondition; import org.chronos.chronodb.api.query.NumberCondition; import org.chronos.chronodb.internal.api.query.searchspec.ContainmentLongSearchSpecification; import org.chronos.chronodb.internal.api.query.searchspec.ContainmentStringSearchSpecification; import org.chronos.chronodb.internal.api.query.searchspec.SearchSpecification; import java.util.Objects; import java.util.Set; public class SetLongWhereElement extends WhereElement<Set<Long>, LongContainmentCondition> { public SetLongWhereElement(final String indexName, LongContainmentCondition condition, Set<Long> comparisonValues){ super(indexName, condition, comparisonValues); } @Override public SetLongWhereElement negate() { return new SetLongWhereElement(this.indexName, this.condition.negate(), this.comparisonValue); } @Override public SearchSpecification<?, ?> toSearchSpecification(SecondaryIndex index) { if(!Objects.equals(index.getName(), this.indexName)){ throw new IllegalArgumentException("Cannot use index '" + index.getName() + "' for search specification - expected index name is '" + this.indexName + "'!"); } return ContainmentLongSearchSpecification.create(index, this.getCondition(), this.getComparisonValue()); } @Override public WhereElement<Set<Long>, LongContainmentCondition> collapseToInClause(final WhereElement<?, ?> other) { if (!this.indexName.equals(other.getIndexName())) { // cannot mix queries on different properties (e.g. firstname and lastname) return null; } if (this.condition.equals(LongContainmentCondition.WITHIN)) { if (other instanceof LongWhereElement) { LongWhereElement otherLongWhere = (LongWhereElement) other; return otherLongWhere.collapseToInClause(this); } else if (other instanceof SetLongWhereElement) { SetLongWhereElement otherSetLongWhere = (SetLongWhereElement) other; if (otherSetLongWhere.getCondition().equals(LongContainmentCondition.WITHIN)) { Set<Long> inClause = Sets.newHashSet(otherSetLongWhere.getComparisonValue()); inClause.addAll(this.comparisonValue); return new SetLongWhereElement(this.indexName, LongContainmentCondition.WITHIN, inClause); } } } else if (this.condition.equals(LongContainmentCondition.WITHOUT)) { if (other instanceof LongWhereElement) { LongWhereElement otherLongWhere = (LongWhereElement) other; return otherLongWhere.collapseToInClause(this); } else if (other instanceof SetLongWhereElement) { SetLongWhereElement otherSetLongWhere = (SetLongWhereElement) other; if (otherSetLongWhere.getCondition().equals(LongContainmentCondition.WITHOUT)) { Set<Long> inClause = Sets.newHashSet(otherSetLongWhere.getComparisonValue()); inClause.addAll(this.comparisonValue); return new SetLongWhereElement(this.indexName, LongContainmentCondition.WITHOUT, inClause); } } } return null; } }
3,524
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
OrToken.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/parser/token/OrToken.java
package org.chronos.chronodb.internal.impl.query.parser.token; import org.chronos.chronodb.internal.impl.query.parser.ast.BinaryQueryOperator; /** * An {@link AndToken} represents a binary relation between two query expressions using the * {@link BinaryQueryOperator#OR}. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public class OrToken implements QueryToken { }
404
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EndToken.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/parser/token/EndToken.java
package org.chronos.chronodb.internal.impl.query.parser.token; import org.chronos.chronodb.internal.api.query.ChronoDBQuery; /** * A {@link EndToken} is used in conjunction with an {@link BeginToken} to form matching braces for precedence handling * in a {@link ChronoDBQuery}. * * <p> * Please note that this is essentially the same as round braces in mathematical expressions. The reason that the * concept is called "begin" and "end" here is that Java does not allow braces for method names. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public class EndToken implements QueryToken { }
632
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AndToken.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/parser/token/AndToken.java
package org.chronos.chronodb.internal.impl.query.parser.token; import org.chronos.chronodb.internal.impl.query.parser.ast.BinaryQueryOperator; /** * An {@link AndToken} represents a binary relation between two query expressions using the * {@link BinaryQueryOperator#AND}. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public class AndToken implements QueryToken { }
406
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
NotToken.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/parser/token/NotToken.java
package org.chronos.chronodb.internal.impl.query.parser.token; /** * A {@link NotToken} negates the result of the subsequent query statements. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public class NotToken implements QueryToken { }
274
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EndOfInputToken.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/parser/token/EndOfInputToken.java
package org.chronos.chronodb.internal.impl.query.parser.token; import org.chronos.chronodb.internal.api.query.QueryTokenStream; /** * An {@link EndOfInputToken} marks the end of the input in an {@link QueryTokenStream}. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public class EndOfInputToken implements QueryToken { }
359
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
QueryToken.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/parser/token/QueryToken.java
package org.chronos.chronodb.internal.impl.query.parser.token; import org.chronos.chronodb.api.builder.query.QueryBuilder; import org.chronos.chronodb.internal.api.query.ChronoDBQuery; /** * A {@link QueryToken} represents a single, lexicographic element in a sequence that defines a {@link ChronoDBQuery}. * * <p> * Instances of classes that implement this interface are usually produced by a {@link QueryBuilder} (or related class). * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public interface QueryToken { }
554
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
BeginToken.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/parser/token/BeginToken.java
package org.chronos.chronodb.internal.impl.query.parser.token; import org.chronos.chronodb.internal.api.query.ChronoDBQuery; /** * A {@link BeginToken} is used in conjunction with an {@link EndToken} to form matching braces for precedence handling * in a {@link ChronoDBQuery}. * * <p> * Please note that this is essentially the same as round braces in mathematical expressions. The reason that the * concept is called "begin" and "end" here is that Java does not allow braces for method names. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public class BeginToken implements QueryToken { }
634
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
KeyspaceToken.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/parser/token/KeyspaceToken.java
package org.chronos.chronodb.internal.impl.query.parser.token; import static com.google.common.base.Preconditions.*; import org.chronos.chronodb.internal.api.query.QueryTokenStream; /** * A {@link KeyspaceToken} is usually the first token in a {@link QueryTokenStream}. It specifies the name of the * keyspace in which the resulting query should be executed. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public class KeyspaceToken implements QueryToken { /** The name of the keyspace in which the query should be executed. */ private final String keyspace; /** * Creates a new {@link KeyspaceToken} with the given keyspace. * * @param keyspace * The keyspace in which the query should be executed. Must not be <code>null</code>. */ public KeyspaceToken(final String keyspace) { checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!"); this.keyspace = keyspace; } /** * Returns the name of the keyspace. * * @return The keyspace name. Never <code>null</code>. */ public String getKeyspace() { return this.keyspace; } }
1,138
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
WhereToken.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/parser/token/WhereToken.java
package org.chronos.chronodb.internal.impl.query.parser.token; import static com.google.common.base.Preconditions.*; import org.chronos.chronodb.api.query.*; import org.chronos.chronodb.internal.impl.query.TextMatchMode; import java.util.Set; /** * A {@link WhereToken} specifies an atomic filter. * * <p> * It consists of three parts: * <ul> * <li><b>Index name:</b> The name of the index to query. * <li><b>Condition:</b> The condition to apply between the value in the index and the comparison value. * <li><b>Comparison value:</b> The value to match against. * </ul> * * For example, let's assume there is an index called "name". A WhereToken could represent the following: * * <pre> * WHERE("name" Condition.EQUALS "Martin") * </pre> * * Structurally, the token consists of an {@link #indexName} and a {@link #whereDetails details} object. The details object varies by the kind of index that is being queried (e.g. {@link StringWhereDetails} for string search, {@link LongWhereDetails} for long search...). * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public class WhereToken implements QueryToken { /** The name of the index to query when evaluating this token. Must not be <code>null</code>. */ private String indexName; /** The details object assigned to this token. */ private AbstractWhereDetails<?, ?> whereDetails; /** * Constructs an empty {@link WhereToken}. * * <p> * Please note that the resulting instance is not valid until all setter methods have been invoked on it. */ public WhereToken() { } /** * Constructs a new {@link WhereToken} and calls {@link #setStringWhereDetails(StringCondition, TextMatchMode, String)} on it. * * @param index * The name of the index to refer in this "where" token. Must not be <code>null</code>. * @param condition * The condition to apply in this "where" token. Must not be <code>null</code>. * @param matchMode * The text match mode to use in this "where" token. See enum literal documentation for details. Must not be <code>null</code>. * @param searchString * The search string to assign to this "where" token. Must not be <code>null</code>. */ public WhereToken(final String index, final StringCondition condition, final TextMatchMode matchMode, final String searchString) { this(); this.setIndexName(index); this.setStringWhereDetails(condition, matchMode, searchString); } /** * Constructs a new {@link WhereToken} and calls {@link #setLongWhereDetails(NumberCondition, long)} on it. * * @param index * The name of the index to refer in this "where" token. Must not be <code>null</code>. * @param condition * The condition to apply in this "where" token. Must not be <code>null</code>. * @param searchValue * The search value to store in this "where" token. */ public WhereToken(final String index, final NumberCondition condition, final long searchValue) { this(); this.setIndexName(index); this.setLongWhereDetails(condition, searchValue); } /** * Constructs a new {@link WhereToken} and calls {@link #setLongWhereDetails(NumberCondition, long)} on it. * * @param index * The name of the index to refer in this "where" token. Must not be <code>null</code>. * @param condition * The condition to apply in this "where" token. Must not be <code>null</code>. * @param searchValue * The search value to store in this "where" token. * @param equalityTolerance * The equality tolerance to store in this "where" token. It is the maximum absolute difference between two doubles that are still considered to be "equal". Must not be negative. */ public WhereToken(final String index, final NumberCondition condition, final double searchValue, final double equalityTolerance) { this(); this.setIndexName(index); this.setDoubleDetails(condition, searchValue, equalityTolerance); } /** * Returns the name of the index. * * @return The index name. Never <code>null</code>. */ public String getIndexName() { if (this.indexName == null) { throw new IllegalStateException("WhereToken#getIndexName() was called before #setIndexName() was called!"); } return this.indexName; } /** * Sets the index name. * * @param indexName * The name of the index. Must not be <code>null</code>. */ public void setIndexName(final String indexName) { checkNotNull(indexName, "Precondition violation - argument 'indexName' must not be NULL!"); this.indexName = indexName; } /** * Sets the {@link StringWhereDetails} on this token. * * <p> * Please note that any {@link WhereToken} can have at most one details object assigned at any point in time. If there already is a details object of a different type attached, this method will throw an {@link IllegalStateException}. If there is a details object of the same type attached, its values will be overwritten. * * @param condition * The condition to store in this "where" token. Must not be <code>null</code>. * @param matchMode * The text match mode to store in this "where" token. Must not be <code>null</code>. * @param comparisonValue * The comparison value to store in this "where" token. Must not be <code>null</code>. */ public void setStringWhereDetails(final StringCondition condition, final TextMatchMode matchMode, final String comparisonValue) { checkNotNull(condition, "Precondition violation - argument 'condition' must not be NULL!"); checkNotNull(matchMode, "Precondition violation - argument 'matchmode' must not be NULL!"); checkNotNull(comparisonValue, "Precondition violation - argument 'comparisonValue' must not be NULL!"); if (this.whereDetails != null && this.whereDetails instanceof StringWhereDetails == false) { throw new IllegalStateException("Attempted to set string search details on a Where token that has search details of a different type assigned!"); } if (this.whereDetails == null) { this.whereDetails = new StringWhereDetails(condition, matchMode, comparisonValue); } else { StringWhereDetails stringWhereDetails = (StringWhereDetails) this.whereDetails; stringWhereDetails.setCondition(condition); stringWhereDetails.setMatchMode(matchMode); stringWhereDetails.setComparisonValue(comparisonValue); } } /** * Sets the {@link LongWhereDetails} on this token. * * <p> * Please note that any {@link WhereToken} can have at most one details object assigned at any point in time. If there already is a details object of a different type attached, this method will throw an {@link IllegalStateException}. If there is a details object of the same type attached, its values will be overwritten. * * @param condition * The condition to store in this "where" token. Must not be <code>null</code>. * @param comparisonValue * The comparison value to store in this "where" token. */ public void setLongWhereDetails(final NumberCondition condition, final long comparisonValue) { checkNotNull(condition, "Precondition violation - argument 'condition' must not be NULL!"); if (this.whereDetails != null && this.whereDetails instanceof LongWhereDetails == false) { throw new IllegalStateException("Attempted to set long search details on a Where token that has search details of a different type assigned!"); } if (this.whereDetails == null) { this.whereDetails = new LongWhereDetails(condition, comparisonValue); } else { LongWhereDetails longWhereDetails = (LongWhereDetails) this.whereDetails; longWhereDetails.setCondition(condition); longWhereDetails.setComparisonValue(comparisonValue); } } /** * Sets the {@link DoubleWhereDetails} on this token. * * <p> * Please note that any {@link WhereToken} can have at most one details object assigned at any point in time. If there already is a details object of a different type attached, this method will throw an {@link IllegalStateException}. If there is a details object of the same type attached, its values will be overwritten. * * @param condition * The condition to store in this "where" token. Must not be <code>null</code>. * @param comparisonValue * The comparison value to store in this "where" token. * @param equalityTolerance * The equality tolerance to store in this "where" token. Must not be negative. */ public void setDoubleDetails(final NumberCondition condition, final double comparisonValue, final double equalityTolerance) { checkNotNull(condition, "Precondition violation - argument 'condition' must not be NULL!"); checkArgument(equalityTolerance >= 0, "Precondition violation - argument 'equalityTolerance' must not be negative!"); if (this.whereDetails != null && this.whereDetails instanceof DoubleWhereDetails == false) { throw new IllegalStateException("Attempted to set double search details on a Where token that has search details of a different type assigned!"); } if (this.whereDetails == null) { this.whereDetails = new DoubleWhereDetails(condition, comparisonValue, equalityTolerance); } else { DoubleWhereDetails doubleWhereDetails = (DoubleWhereDetails) this.whereDetails; doubleWhereDetails.setCondition(condition); doubleWhereDetails.setComparisonValue(comparisonValue); doubleWhereDetails.setEqualityTolerance(equalityTolerance); } } /** * Sets the {@link SetStringWhereDetails} on this token. * * <p> * Please note that any {@link WhereToken} can have at most one details object assigned at any point in time. If there already is a details object of a different type attached, this method will throw an {@link IllegalStateException}. If there is a details object of the same type attached, its values will be overwritten. * * @param condition * The condition to store in this "where" token. Must not be <code>null</code>. * @param matchMode * The text match mode to store in this "where" token. Must not be <code>null</code>. * @param comparisonValues * The comparison value to store in this "where" token. Must not be <code>null</code>. */ public void setSetStringWhereDetails(final StringContainmentCondition condition, final TextMatchMode matchMode, final Set<String> comparisonValues) { checkNotNull(condition, "Precondition violation - argument 'condition' must not be NULL!"); checkNotNull(matchMode, "Precondition violation - argument 'matchmode' must not be NULL!"); checkNotNull(comparisonValues, "Precondition violation - argument 'comparisonValue' must not be NULL!"); if (this.whereDetails != null && this.whereDetails instanceof SetStringWhereDetails == false) { throw new IllegalStateException("Attempted to set string containment search details on a Where token that has search details of a different type assigned!"); } if (this.whereDetails == null) { this.whereDetails = new SetStringWhereDetails(condition, matchMode, comparisonValues); } else { SetStringWhereDetails stringWhereDetails = (SetStringWhereDetails) this.whereDetails; stringWhereDetails.setCondition(condition); stringWhereDetails.setMatchMode(matchMode); stringWhereDetails.setComparisonValue(comparisonValues); } } /** * Sets the {@link SetLongWhereDetails} on this token. * * <p> * Please note that any {@link WhereToken} can have at most one details object assigned at any point in time. If there already is a details object of a different type attached, this method will throw an {@link IllegalStateException}. If there is a details object of the same type attached, its values will be overwritten. * * @param condition * The condition to store in this "where" token. Must not be <code>null</code>. * @param comparisonValues * The comparison value to store in this "where" token. */ public void setSetLongWhereDetails(final LongContainmentCondition condition, final Set<Long> comparisonValues) { checkNotNull(condition, "Precondition violation - argument 'condition' must not be NULL!"); if (this.whereDetails != null && this.whereDetails instanceof SetLongWhereDetails == false) { throw new IllegalStateException("Attempted to set long containment search details on a Where token that has search details of a different type assigned!"); } if (this.whereDetails == null) { this.whereDetails = new SetLongWhereDetails(condition, comparisonValues); } else { SetLongWhereDetails longWhereDetails = (SetLongWhereDetails) this.whereDetails; longWhereDetails.setCondition(condition); longWhereDetails.setComparisonValue(comparisonValues); } } /** * Sets the {@link SetDoubleWhereDetails} on this token. * * <p> * Please note that any {@link WhereToken} can have at most one details object assigned at any point in time. If there already is a details object of a different type attached, this method will throw an {@link IllegalStateException}. If there is a details object of the same type attached, its values will be overwritten. * * @param condition * The condition to store in this "where" token. Must not be <code>null</code>. * @param comparisonValues * The comparison value to store in this "where" token. * @param equalityTolerance * The equality tolerance to store in this "where" token. Must not be negative. */ public void setSetDoubleDetails(final DoubleContainmentCondition condition, final Set<Double> comparisonValues, final double equalityTolerance) { checkNotNull(condition, "Precondition violation - argument 'condition' must not be NULL!"); checkArgument(equalityTolerance >= 0, "Precondition violation - argument 'equalityTolerance' must not be negative!"); if (this.whereDetails != null && this.whereDetails instanceof SetDoubleWhereDetails == false) { throw new IllegalStateException("Attempted to set double containment search details on a Where token that has search details of a different type assigned!"); } if (this.whereDetails == null) { this.whereDetails = new SetDoubleWhereDetails(condition, comparisonValues, equalityTolerance); } else { SetDoubleWhereDetails doubleWhereDetails = (SetDoubleWhereDetails) this.whereDetails; doubleWhereDetails.setCondition(condition); doubleWhereDetails.setComparisonValue(comparisonValues); doubleWhereDetails.setEqualityTolerance(equalityTolerance); } } /** * Returns the {@link StringWhereDetails} attached to this element. * * <p> * Please note that a {@link WhereToken} can have at most one "details" object attached. If there is no details object attached, or a details object of a different type is attached, then this method will throw an {@link IllegalStateException}. Use {@link #isStringWhereToken()} first to check if calling this method is safe or not. * * @return The details object. Never <code>null</code>. * * @throws IllegalStateException * Thrown if no details object is present or it is of the wrong type. */ public StringWhereDetails asStringWhereToken() { if (this.whereDetails == null) { throw new IllegalStateException("Requested the Where details for String search, but no details have been assigned yet!"); } if (this.whereDetails instanceof StringWhereDetails == false) { throw new IllegalStateException("Requested the Where details for String search, but details of a different type were assigned!"); } return (StringWhereDetails) this.whereDetails; } /** * Returns the {@link LongWhereDetails} attached to this element. * * <p> * Please note that a {@link WhereToken} can have at most one "details" object attached. If there is no details object attached, or a details object of a different type is attached, then this method will throw an {@link IllegalStateException}. Use {@link #isLongWhereToken()} first to check if calling this method is safe or not. * * @return The details object. Never <code>null</code>. * * @throws IllegalStateException * Thrown if no details object is present or it is of the wrong type. */ public LongWhereDetails asLongWhereToken() { if (this.whereDetails == null) { throw new IllegalStateException("Requested the Where details for Long search, but no details have been assigned yet!"); } if (this.whereDetails instanceof LongWhereDetails == false) { throw new IllegalStateException("Requested the Where details for Long search, but details of a different type were assigned!"); } return (LongWhereDetails) this.whereDetails; } /** * Returns the {@link DoubleWhereDetails} attached to this element. * * <p> * Please note that a {@link WhereToken} can have at most one "details" object attached. If there is no details object attached, or a details object of a different type is attached, then this method will throw an {@link IllegalStateException}. Use {@link #isDoubleWhereToken()} first to check if calling this method is safe or not. * * @return The details object. Never <code>null</code>. * * @throws IllegalStateException * Thrown if no details object is present or it is of the wrong type. */ public DoubleWhereDetails asDoubleWhereToken() { if (this.whereDetails == null) { throw new IllegalStateException("Requested the Where details for Double search, but no details have been assigned yet!"); } if (this.whereDetails instanceof DoubleWhereDetails == false) { throw new IllegalStateException("Requested the Where details for Double search, but details of a different type were assigned!"); } return (DoubleWhereDetails) this.whereDetails; } /** * Returns the {@link SetStringWhereDetails} attached to this element. * * <p> * Please note that a {@link WhereToken} can have at most one "details" object attached. If there is no details object attached, or a details object of a different type is attached, then this method will throw an {@link IllegalStateException}. Use {@link #isStringWhereToken()} first to check if calling this method is safe or not. * * @return The details object. Never <code>null</code>. * * @throws IllegalStateException * Thrown if no details object is present or it is of the wrong type. */ public SetStringWhereDetails asSetStringWhereToken() { if (this.whereDetails == null) { throw new IllegalStateException("Requested the Where details for String Containment search, but no details have been assigned yet!"); } if (this.whereDetails instanceof SetStringWhereDetails == false) { throw new IllegalStateException("Requested the Where details for String Containment search, but details of a different type were assigned!"); } return (SetStringWhereDetails) this.whereDetails; } /** * Returns the {@link SetLongWhereDetails} attached to this element. * * <p> * Please note that a {@link WhereToken} can have at most one "details" object attached. If there is no details object attached, or a details object of a different type is attached, then this method will throw an {@link IllegalStateException}. Use {@link #isLongWhereToken()} first to check if calling this method is safe or not. * * @return The details object. Never <code>null</code>. * * @throws IllegalStateException * Thrown if no details object is present or it is of the wrong type. */ public SetLongWhereDetails asSetLongWhereToken() { if (this.whereDetails == null) { throw new IllegalStateException("Requested the Where details for Long Containment search, but no details have been assigned yet!"); } if (this.whereDetails instanceof SetLongWhereDetails == false) { throw new IllegalStateException("Requested the Where details for Long Containment search, but details of a different type were assigned!"); } return (SetLongWhereDetails) this.whereDetails; } /** * Returns the {@link SetDoubleWhereDetails} attached to this element. * * <p> * Please note that a {@link WhereToken} can have at most one "details" object attached. If there is no details object attached, or a details object of a different type is attached, then this method will throw an {@link IllegalStateException}. Use {@link #isDoubleWhereToken()} first to check if calling this method is safe or not. * * @return The details object. Never <code>null</code>. * * @throws IllegalStateException * Thrown if no details object is present or it is of the wrong type. */ public SetDoubleWhereDetails asSetDoubleWhereToken() { if (this.whereDetails == null) { throw new IllegalStateException("Requested the Where details for Double Containment search, but no details have been assigned yet!"); } if (this.whereDetails instanceof SetDoubleWhereDetails == false) { throw new IllegalStateException("Requested the Where details for Double Containment search, but details of a different type were assigned!"); } return (SetDoubleWhereDetails) this.whereDetails; } /** * Checks if this element has {@link StringWhereDetails} assigned to it. * * @return <code>true</code> if StringWhereDetails are assigned, otherwise <code>false</code>. */ public boolean isStringWhereToken() { return this.whereDetails instanceof StringWhereDetails; } /** * Checks if this element has {@link LongWhereDetails} assigned to it. * * @return <code>true</code> if LongWhereDetails are assigned, otherwise <code>false</code>. */ public boolean isLongWhereToken() { return this.whereDetails instanceof LongWhereDetails; } /** * Checks if this element has {@link DoubleWhereDetails} assigned to it. * * @return <code>true</code> if DoubleWhereDetails are assigned, otherwise <code>false</code>. */ public boolean isDoubleWhereToken() { return this.whereDetails instanceof DoubleWhereDetails; } /** * Checks if this element has {@link SetStringWhereDetails} assigned to it. * * @return <code>true</code> if SetStringWhereDetails are assigned, otherwise <code>false</code>. */ public boolean isSetStringWhereToken() { return this.whereDetails instanceof SetStringWhereDetails; } /** * Checks if this element has {@link SetLongWhereDetails} assigned to it. * * @return <code>true</code> if SetLongWhereDetails are assigned, otherwise <code>false</code>. */ public boolean isSetLongWhereToken() { return this.whereDetails instanceof SetLongWhereDetails; } /** * Checks if this element has {@link SetDoubleWhereDetails} assigned to it. * * @return <code>true</code> if SetDoubleWhereDetails are assigned, otherwise <code>false</code>. */ public boolean isSetDoubleWhereToken() { return this.whereDetails instanceof SetDoubleWhereDetails; } /** * Checks if this element already has {@linkplain AbstractWhereDetails details} assigned to it. * * @return <code>true</code> if details are present, otherwise <code>false</code>. */ public boolean hasDetailsAssigned() { return this.whereDetails != null; } /** * A simple data container, specifying the details of a {@link WhereToken} in the query language. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * @param <VALUE> * The type of the comparison value to store. * @param <CONDITION> * The type of the {@linkplain Condition comparison condition} to store. */ public abstract class AbstractWhereDetails<VALUE, CONDITION extends Condition> { /** The comparison condition to apply between the indexed values and the {@link #comparisonValue}. */ protected CONDITION condition; /** The comparison value, i.e. the value that will be {@linkplain #condition compared} against the indexed values. */ protected VALUE comparisonValue; /** * Constructs a full {@link StringWhereDetails}. * * @param condition * The condition to apply. Must not be <code>null</code>. * @param comparisonValue * The value to compare the indexed values against by applying the condition. Must not be <code>null</code>. */ protected AbstractWhereDetails(final CONDITION condition, final VALUE comparisonValue) { checkNotNull(condition, "Precondition violation - argument 'condition' must not be NULL!"); checkNotNull(comparisonValue, "Precondition violation - argument 'comparisonValue' must not be NULL!"); this.condition = condition; this.comparisonValue = comparisonValue; } /** * Returns the condition to apply. * * @return The condition. Never <code>null</code>. */ public CONDITION getCondition() { if (this.condition == null) { throw new IllegalStateException("WhereToken#getCondition() was called before #setCondition() was called!"); } return this.condition; } /** * Sets the condition to apply. * * @param condition * The condition to apply. Must not be <code>null</code>. */ public void setCondition(final CONDITION condition) { checkNotNull(condition, "Precondition violation - argument 'condition' must not be NULL!"); this.condition = condition; } /** * Returns the comparison value. * * @return The comparison value. Never <code>null</code>. */ public VALUE getComparisonValue() { if (this.comparisonValue == null) { throw new IllegalStateException( "WhereToken#getComparisonValue() was called before #setComparisonValue() was called!"); } return this.comparisonValue; } /** * Sets the comparison value. * * @param comparisonValue * The comparison value to use. Must not be <code>null</code>. */ public void setComparisonValue(final VALUE comparisonValue) { checkNotNull(comparisonValue, "Precondition violation - argument 'comparisonValue' must not be NULL!"); this.comparisonValue = comparisonValue; } /** * Returns the name of the index to scan. * * @return The index name. Never <code>null</code>. */ public String getIndexName() { return WhereToken.this.getIndexName(); } /** * Sets the index name. * * @param indexName * The name of the index. Must not be <code>null</code>. */ public void setIndexName(final String indexName) { WhereToken.this.setIndexName(indexName); } } /** * A simple data container, specifying the details of a {@link WhereToken} in the query language. * * <p> * This version is specialized for "where" clauses that act on {@link String} values. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API */ public class StringWhereDetails extends AbstractWhereDetails<String, StringCondition> { /** The match mode to apply when comparing two strings. See enum literals for details. */ private TextMatchMode matchMode = TextMatchMode.STRICT; /** * Constructs a full {@link StringWhereDetails}. * * @param condition * The condition to apply. Must not be <code>null</code>. * @param matchMode * The text match mode to use. Must not be <code>null</code>. * @param comparisonValue * The value to compare the indexed values against by applying the condition. Must not be <code>null</code>. */ public StringWhereDetails(final StringCondition condition, final TextMatchMode matchMode, final String comparisonValue) { super(condition, comparisonValue); checkNotNull(matchMode, "Precondition violation - argument 'matchMode' must not be NULL!"); this.matchMode = matchMode; } /** * Returns the match mode. * * @return The match mode. Never <code>null</code>. */ public TextMatchMode getMatchMode() { return this.matchMode; } /** * Sets the match mode to use. * * @param matchMode * The match mode to use. Must not be <code>null</code>. */ public void setMatchMode(final TextMatchMode matchMode) { checkNotNull(matchMode, "Precondition violation - argument 'matchMode' must not be NULL!"); this.matchMode = matchMode; } } /** * A simple data container, specifying the details of a {@link WhereToken} in the query language. * * <p> * This version is specialized for "where" clauses that act on {@link Long} values. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API */ public class LongWhereDetails extends AbstractWhereDetails<Long, NumberCondition> { /** * Creates a new {@link LongWhereDetails} instance. * * @param condition * The condition to store in the new details object. Must not be <code>null</code>. * @param comparisonValue * The comparison value to store in the new details object. */ protected LongWhereDetails(final NumberCondition condition, final long comparisonValue) { super(condition, comparisonValue); } } /** * A simple data container, specifying the details of a {@link WhereToken} in the query language. * * <p> * This version is specialized for "where" clauses that act on {@link Double} values. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API */ public class DoubleWhereDetails extends AbstractWhereDetails<Double, NumberCondition> { /** The equality tolerance, i.e. the absolute value by which two doubles may differ but still be considered equal. */ private double equalityTolerance; /** * Creates a new {@link DoubleWhereDetails} instance. * * @param condition * The condition to store in the new details object. Must not be <code>null</code>. * @param comparisonValue * The comparison value to store in the new details object. * @param equalityTolerance * The equality tolerance to store in the new details object. Must not be negative. For details, see {@link #setEqualityTolerance(double)}. */ protected DoubleWhereDetails(final NumberCondition condition, final double comparisonValue, final double equalityTolerance) { super(condition, comparisonValue); checkArgument(equalityTolerance >= 0, "Precondition violation - argument 'equalityTolerance' must not be negative!"); this.equalityTolerance = equalityTolerance; } /** * Returns the assigned equality tolerance. * * <p> * The equality tolerance is the (absolute) value by which two double values can differ and still be considered equal. * * @return The equality tolerance. Never negative. */ public double getEqualityTolerance() { return this.equalityTolerance; } /** * Sets the equality tolerance. * * <p> * The equality tolerance is the (absolute) value by which two double values can differ and still be considered equal. * * * @param equalityTolerance * The equality tolerance to use. Must not be negative. */ public void setEqualityTolerance(final double equalityTolerance) { checkArgument(equalityTolerance >= 0, "Precondition violation - argument 'equalityTolerance' must not be negative!"); this.equalityTolerance = equalityTolerance; } } /** * A simple data container, specifying the details of a {@link WhereToken} in the query language. * * <p> * This version is specialized for "where" clauses that act on {@link Set<String>} values. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API */ public class SetStringWhereDetails extends AbstractWhereDetails<Set<String>, StringContainmentCondition> { /** The match mode to apply when comparing two strings. See enum literals for details. */ private TextMatchMode matchMode = TextMatchMode.STRICT; /** * Constructs a full {@link SetStringWhereDetails}. * * @param condition * The condition to apply. Must not be <code>null</code>. * @param matchMode * The text match mode to use. Must not be <code>null</code>. * @param comparisonValues * The value to compare the indexed values against by applying the condition. Must not be <code>null</code>. */ public SetStringWhereDetails(final StringContainmentCondition condition, final TextMatchMode matchMode, final Set<String> comparisonValues) { super(condition, comparisonValues); checkNotNull(matchMode, "Precondition violation - argument 'matchMode' must not be NULL!"); this.matchMode = matchMode; } /** * Returns the match mode. * * @return The match mode. Never <code>null</code>. */ public TextMatchMode getMatchMode() { return this.matchMode; } /** * Sets the match mode to use. * * @param matchMode * The match mode to use. Must not be <code>null</code>. */ public void setMatchMode(final TextMatchMode matchMode) { checkNotNull(matchMode, "Precondition violation - argument 'matchMode' must not be NULL!"); this.matchMode = matchMode; } } /** * A simple data container, specifying the details of a {@link WhereToken} in the query language. * * <p> * This version is specialized for "where" clauses that act on {@link Set<Long>} values. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API */ public class SetLongWhereDetails extends AbstractWhereDetails<Set<Long>, LongContainmentCondition> { /** * Creates a new {@link LongWhereDetails} instance. * * @param condition * The condition to store in the new details object. Must not be <code>null</code>. * @param comparisonValues * The comparison value to store in the new details object. */ protected SetLongWhereDetails(final LongContainmentCondition condition, final Set<Long> comparisonValues) { super(condition, comparisonValues); } } /** * A simple data container, specifying the details of a {@link WhereToken} in the query language. * * <p> * This version is specialized for "where" clauses that act on {@link Set<Double>} values. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API */ public class SetDoubleWhereDetails extends AbstractWhereDetails<Set<Double>, DoubleContainmentCondition> { /** The equality tolerance, i.e. the absolute value by which two doubles may differ but still be considered equal. */ private double equalityTolerance; /** * Creates a new {@link SetDoubleWhereDetails} instance. * * @param condition * The condition to store in the new details object. Must not be <code>null</code>. * @param comparisonValues * The comparison value to store in the new details object. * @param equalityTolerance * The equality tolerance to store in the new details object. Must not be negative. For details, see {@link #setEqualityTolerance(double)}. */ protected SetDoubleWhereDetails(final DoubleContainmentCondition condition, final Set<Double> comparisonValues, final double equalityTolerance) { super(condition, comparisonValues); checkArgument(equalityTolerance >= 0, "Precondition violation - argument 'equalityTolerance' must not be negative!"); this.equalityTolerance = equalityTolerance; } /** * Returns the assigned equality tolerance. * * <p> * The equality tolerance is the (absolute) value by which two double values can differ and still be considered equal. * * @return The equality tolerance. Never negative. */ public double getEqualityTolerance() { return this.equalityTolerance; } /** * Sets the equality tolerance. * * <p> * The equality tolerance is the (absolute) value by which two double values can differ and still be considered equal. * * * @param equalityTolerance * The equality tolerance to use. Must not be negative. */ public void setEqualityTolerance(final double equalityTolerance) { checkArgument(equalityTolerance >= 0, "Precondition violation - argument 'equalityTolerance' must not be negative!"); this.equalityTolerance = equalityTolerance; } } }
36,005
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
NegatedCondition.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/condition/NegatedCondition.java
package org.chronos.chronodb.internal.impl.query.condition; import org.chronos.chronodb.api.query.Condition; public interface NegatedCondition extends Condition { @Override default boolean isNegated() { return true; } }
229
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
NotEqualsCondition.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/condition/NotEqualsCondition.java
package org.chronos.chronodb.internal.impl.query.condition; public class NotEqualsCondition extends AbstractCondition implements NegatedStringCondition, NegatedNumberCondition { // ================================================================================================================= // FIELDS // ================================================================================================================= public static final NotEqualsCondition INSTANCE = new NotEqualsCondition(); // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= protected NotEqualsCondition() { super("<>"); } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public boolean acceptsEmptyValue() { return true; } @Override public EqualsCondition negate() { return EqualsCondition.INSTANCE; } @Override public String toString() { return "NotEquals"; } }
1,284
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
NegatedStringCondition.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/main/java/org/chronos/chronodb/internal/impl/query/condition/NegatedStringCondition.java
package org.chronos.chronodb.internal.impl.query.condition; import org.chronos.chronodb.api.query.StringCondition; import org.chronos.chronodb.internal.impl.query.TextMatchMode; public interface NegatedStringCondition extends StringCondition, NegatedCondition { @Override public StringCondition negate(); @Override default boolean applies(final String text, final String searchValue, final TextMatchMode matchMode) { return this.negate().applies(text, searchValue, matchMode) == false; } }
501
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z