diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 1121a3807..07ee48921 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -17,23 +17,22 @@ on:
- "README.md"
jobs:
- build:
- runs-on: ${{ matrix.os }}
+ build_linux:
+ runs-on: ubuntu-latest
strategy:
matrix:
java: ['11', '17']
- os: ['ubuntu-latest']
env:
JAVA_OPTS: "-XX:+TieredCompilation -XX:TieredStopAtLevel=1"
MAVEN_USERNAME: ${{ secrets.OSSRH_USER }}
MAVEN_PASSWORD: ${{ secrets.OSSRH_PASSWORD }}
PGP_KEY_ID: ${{ secrets.PGP_KEY_ID }}
PGP_KEY_PASSWORD: ${{ secrets.PGP_KEY_PASSWORD }}
- name: Build with Java ${{ matrix.java }} on ${{ matrix.os }}
+ name: Build with Java ${{ matrix.java }} in Ubuntu
steps:
- - uses: actions/checkout@v4
- - name: Set up JDK ${{ matrix.java }} on ${{ matrix.os }}
+ - uses: actions/checkout@v3
+ - name: Set up JDK ${{ matrix.java }}
uses: actions/setup-java@v3
with:
java-version: ${{ matrix.java }}
@@ -55,7 +54,7 @@ jobs:
run: mvn -B -ff -ntp clean install
- name: Deploy Snapshot
- if: github.ref == 'refs/heads/develop'
+ if: github.ref == 'refs/heads/develop' && matrix.java == '11'
run: mvn -B -ff -ntp deploy -DskipTests
env:
MAVEN_USERNAME: ${{ secrets.OSSRH_USER }}
@@ -64,7 +63,7 @@ jobs:
PGP_KEY_PASSWORD: ${{ secrets.PGP_KEY_PASSWORD }}
- name: Deploy Release
- if: github.ref == 'refs/heads/release'
+ if: github.ref == 'refs/heads/release' && matrix.java == '11'
run: mvn -B -ff -ntp release:clean release:prepare release:perform -DskipTests
env:
MAVEN_USERNAME: ${{ secrets.OSSRH_USER }}
@@ -73,9 +72,55 @@ jobs:
PGP_KEY_PASSWORD: ${{ secrets.PGP_KEY_PASSWORD }}
- name: Publish Code Coverage
- if: github.ref == 'refs/heads/main'
+ if: github.ref == 'refs/heads/main' && matrix.java == '11'
uses: codecov/codecov-action@v3
with:
token: ${{ secrets.CODECOV_TOKEN }}
flags: unittests
- name: codecov-umbrella
\ No newline at end of file
+ name: codecov-umbrella
+
+ build_macos:
+ runs-on: macos-latest
+ strategy:
+ matrix:
+ java: [ '11', '17' ]
+ env:
+ JAVA_OPTS: "-XX:+TieredCompilation -XX:TieredStopAtLevel=1"
+
+ name: Build with Java ${{ matrix.java }} in MacOS
+ steps:
+ - uses: actions/checkout@v3
+ - name: Set up JDK ${{ matrix.java }}
+ uses: actions/setup-java@v3
+ with:
+ java-version: ${{ matrix.java }}
+ distribution: 'zulu'
+ java-package: jdk
+ architecture: x64
+ cache: 'maven'
+
+ - name: Build with Maven
+ run: mvn -B -ff -ntp clean install
+
+ build_windows:
+ runs-on: windows-latest
+ strategy:
+ matrix:
+ java: [ '11', '17' ]
+ env:
+ JAVA_OPTS: "-XX:+TieredCompilation -XX:TieredStopAtLevel=1"
+
+ name: Build with Java ${{ matrix.java }} in Windows
+ steps:
+ - uses: actions/checkout@v3
+ - name: Set up JDK ${{ matrix.java }}
+ uses: actions/setup-java@v3
+ with:
+ java-version: ${{ matrix.java }}
+ distribution: 'zulu'
+ java-package: jdk
+ architecture: x64
+ cache: 'maven'
+
+ - name: Build with Maven
+ run: mvn -B -ff -ntp clean install
\ No newline at end of file
diff --git a/README.md b/README.md
index d90df8c1a..d2ec139ff 100644
--- a/README.md
+++ b/README.md
@@ -7,11 +7,11 @@
[](https://github.com/nitrite/nitrite-java/discussions)
org.apache.maven.plugins
diff --git a/nitrite-jackson-mapper/src/main/java/org/dizitart/no2/common/mapper/JacksonMapper.java b/nitrite-jackson-mapper/src/main/java/org/dizitart/no2/common/mapper/JacksonMapper.java
index 282d83aaa..951eae0f3 100644
--- a/nitrite-jackson-mapper/src/main/java/org/dizitart/no2/common/mapper/JacksonMapper.java
+++ b/nitrite-jackson-mapper/src/main/java/org/dizitart/no2/common/mapper/JacksonMapper.java
@@ -20,11 +20,11 @@
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.*;
-import lombok.extern.slf4j.Slf4j;
import org.dizitart.no2.NitriteConfig;
import org.dizitart.no2.collection.Document;
import org.dizitart.no2.common.mapper.modules.NitriteIdModule;
import org.dizitart.no2.exceptions.ObjectMappingException;
+import org.dizitart.no2.exceptions.ValidationException;
import java.io.IOException;
import java.util.*;
@@ -32,20 +32,29 @@
import static org.dizitart.no2.common.util.ValidationUtils.notNull;
/**
+ * A {@link NitriteMapper} implementation that uses Jackson ObjectMapper to
+ * convert objects to and from Nitrite document.
+ *
+ * @since 4.0
+ * @see NitriteMapper
* @author Anindya Chatterjee
*/
-@Slf4j
public class JacksonMapper implements NitriteMapper {
private ObjectMapper objectMapper;
+ /**
+ * Returns the object mapper instance used for document conversion.
+ *
+ * @return the object mapper instance used for document conversion
+ */
protected ObjectMapper getObjectMapper() {
if (objectMapper == null) {
objectMapper = new ObjectMapper();
objectMapper.setVisibility(
- objectMapper.getSerializationConfig().getDefaultVisibilityChecker()
- .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
- .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
- .withIsGetterVisibility(JsonAutoDetect.Visibility.NONE));
+ objectMapper.getSerializationConfig().getDefaultVisibilityChecker()
+ .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
+ .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
+ .withIsGetterVisibility(JsonAutoDetect.Visibility.NONE));
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
@@ -55,11 +64,34 @@ protected ObjectMapper getObjectMapper() {
return objectMapper;
}
+ /**
+ * Registers a Jackson module with the object mapper.
+ *
+ * @param module the Jackson module to register
+ * @throws ValidationException if the module is null
+ */
public void registerJacksonModule(Module module) {
notNull(module, "module cannot be null");
getObjectMapper().registerModule(module);
}
+ /**
+ * Tries to convert the given source object to the target type using Jackson
+ * ObjectMapper.
+ *
+ * If the source object is null, returns null. If the source
+ * object is a value node, returns the node value. If the target type is
+ * Document, converts the source object to a Document. If the source object is
+ * already a Document, converts it to the target type. If the conversion fails,
+ * throws an ObjectMappingException.
+ *
+ * @param source the source object to convert
+ * @param type the target type to convert to
+ * @param the type of the source object
+ * @param the type of the target object
+ * @return the converted object of the target type
+ * @throws ObjectMappingException if the conversion fails
+ */
@Override
public Object tryConvert(Source source, Class type) {
if (source == null) {
@@ -68,7 +100,8 @@ public Object tryConvert(Source source, Class type) {
try {
JsonNode node = getObjectMapper().convertValue(source, JsonNode.class);
- if (node == null) return null;
+ if (node == null)
+ return null;
if (node.isValueNode()) {
return getNodeValue(node);
@@ -81,18 +114,28 @@ public Object tryConvert(Source source, Class type) {
}
} catch (Exception e) {
throw new ObjectMappingException("Failed to convert object of type "
- + source.getClass() + " to type " + type, e);
+ + source.getClass() + " to type " + type, e);
}
throw new ObjectMappingException("Can't convert object to type " + type
- + ", try registering a jackson Module for it.");
+ + ", try registering a jackson Module for it.");
}
-
@Override
public void initialize(NitriteConfig nitriteConfig) {
}
+ /**
+ * Converts a Nitrite Document to an object of the specified class type using
+ * Jackson ObjectMapper.
+ *
+ * @param source the Nitrite Document to be converted
+ * @param type the class type of the object to be converted to
+ * @param the type of the object to be converted to
+ * @return the converted object of the specified class type
+ * @throws ObjectMappingException if there is an error in the object mapping
+ * process
+ */
protected Target convertFromDocument(Document source, Class type) {
try {
return getObjectMapper().convertValue(source, type);
@@ -107,6 +150,14 @@ protected Target convertFromDocument(Document source, Class typ
}
}
+ /**
+ * Converts the given source object to a Nitrite {@link Document} using
+ * Jackson's {@link ObjectMapper}.
+ *
+ * @param source the source object to convert
+ * @param the type of the source object
+ * @return the converted Nitrite {@link Document}
+ */
protected Document convertToDocument(Source source) {
JsonNode node = getObjectMapper().convertValue(source, JsonNode.class);
return readDocument(node);
@@ -168,7 +219,7 @@ private Object readObject(JsonNode node) {
return null;
}
- @SuppressWarnings({"unchecked", "rawtypes"})
+ @SuppressWarnings({ "unchecked", "rawtypes" })
private List readArray(JsonNode array) {
if (array.isArray()) {
List list = new ArrayList();
diff --git a/nitrite-jackson-mapper/src/main/java/org/dizitart/no2/common/mapper/JacksonMapperModule.java b/nitrite-jackson-mapper/src/main/java/org/dizitart/no2/common/mapper/JacksonMapperModule.java
index 7b7d6d55d..47edf3429 100644
--- a/nitrite-jackson-mapper/src/main/java/org/dizitart/no2/common/mapper/JacksonMapperModule.java
+++ b/nitrite-jackson-mapper/src/main/java/org/dizitart/no2/common/mapper/JacksonMapperModule.java
@@ -25,15 +25,30 @@
import static org.dizitart.no2.common.util.Iterables.setOf;
/**
+ * A Nitrite module that provides a jackson based {@link NitriteMapper}
+ * implementation for object to document conversion.
+ *
+ * @since 4.0
+ * @see NitriteMapper
+ * @see JacksonMapper
* @author Anindya Chatterjee
*/
public class JacksonMapperModule implements NitriteModule {
private final JacksonMapper jacksonMapper;
+ /**
+ * Instantiates a new {@link JacksonMapperModule}.
+ */
public JacksonMapperModule() {
jacksonMapper = new JacksonMapper();
}
+ /**
+ * Instantiates a new {@link JacksonMapperModule} with custom
+ * jackson modules.
+ *
+ * @param jacksonModules the jackson modules
+ */
public JacksonMapperModule(Module... jacksonModules) {
jacksonMapper = new JacksonMapper();
for (Module jacksonModule : jacksonModules) {
diff --git a/nitrite-jackson-mapper/src/main/java/org/dizitart/no2/common/mapper/modules/NitriteIdDeserializer.java b/nitrite-jackson-mapper/src/main/java/org/dizitart/no2/common/mapper/modules/NitriteIdDeserializer.java
index ca07c4c6f..701996982 100644
--- a/nitrite-jackson-mapper/src/main/java/org/dizitart/no2/common/mapper/modules/NitriteIdDeserializer.java
+++ b/nitrite-jackson-mapper/src/main/java/org/dizitart/no2/common/mapper/modules/NitriteIdDeserializer.java
@@ -24,6 +24,7 @@
import java.io.IOException;
/**
+ * @since 4.0
* @author Anindya Chatterjee
*/
class NitriteIdDeserializer extends StdScalarDeserializer {
diff --git a/nitrite-jackson-mapper/src/main/java/org/dizitart/no2/common/mapper/modules/NitriteIdSerializer.java b/nitrite-jackson-mapper/src/main/java/org/dizitart/no2/common/mapper/modules/NitriteIdSerializer.java
index 1b6b34e2b..e2402e1d1 100644
--- a/nitrite-jackson-mapper/src/main/java/org/dizitart/no2/common/mapper/modules/NitriteIdSerializer.java
+++ b/nitrite-jackson-mapper/src/main/java/org/dizitart/no2/common/mapper/modules/NitriteIdSerializer.java
@@ -24,6 +24,7 @@
import java.io.IOException;
/**
+ * @since 4.0
* @author Anindya Chatterjee
*/
class NitriteIdSerializer extends StdScalarSerializer {
diff --git a/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/migrate/MigrationTest.java b/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/migrate/MigrationTest.java
index f0920e5c6..9fe8f6b05 100644
--- a/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/migrate/MigrationTest.java
+++ b/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/migrate/MigrationTest.java
@@ -26,20 +26,18 @@
import org.dizitart.no2.common.mapper.JacksonMapperModule;
import org.dizitart.no2.exceptions.MigrationException;
import org.dizitart.no2.index.IndexType;
+import org.dizitart.no2.integration.repository.Retry;
+import org.dizitart.no2.integration.repository.TestUtil;
import org.dizitart.no2.migration.InstructionSet;
import org.dizitart.no2.migration.Migration;
import org.dizitart.no2.migration.TypeConverter;
import org.dizitart.no2.mvstore.MVStoreModule;
import org.dizitart.no2.repository.ObjectRepository;
-import org.dizitart.no2.integration.repository.Retry;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Paths;
import java.util.UUID;
import static org.dizitart.no2.filters.FluentFilter.where;
@@ -66,12 +64,12 @@ public void setUp() {
}
@After
- public void cleanUp() throws IOException {
+ public void cleanUp() {
if (!db.isClosed()) {
db.close();
}
- Files.delete(Paths.get(dbPath));
+ TestUtil.deleteDb(dbPath);
}
@Test
diff --git a/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/BaseObjectRepositoryTest.java b/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/BaseObjectRepositoryTest.java
index 607403048..0e9b2a14a 100644
--- a/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/BaseObjectRepositoryTest.java
+++ b/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/BaseObjectRepositoryTest.java
@@ -31,8 +31,6 @@
import org.junit.runners.Parameterized;
import java.io.File;
-import java.nio.file.Files;
-import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collection;
import java.util.UUID;
@@ -180,7 +178,7 @@ public void clear() throws Exception {
}
if (!inMemory) {
- Files.delete(Paths.get(fileName));
+ TestUtil.deleteDb(fileName);
}
}
}
diff --git a/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/CustomFieldSeparatorTest.java b/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/CustomFieldSeparatorTest.java
index 760b19067..888a31550 100644
--- a/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/CustomFieldSeparatorTest.java
+++ b/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/CustomFieldSeparatorTest.java
@@ -25,21 +25,18 @@
import org.dizitart.no2.NitriteConfig;
import org.dizitart.no2.common.mapper.JacksonMapperModule;
import org.dizitart.no2.index.IndexType;
+import org.dizitart.no2.integration.repository.data.Company;
+import org.dizitart.no2.integration.repository.data.Note;
import org.dizitart.no2.mvstore.MVStoreModule;
import org.dizitart.no2.repository.ObjectRepository;
import org.dizitart.no2.repository.annotations.Id;
import org.dizitart.no2.repository.annotations.Index;
import org.dizitart.no2.repository.annotations.Indices;
-import org.dizitart.no2.integration.repository.data.Company;
-import org.dizitart.no2.integration.repository.data.Note;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
-import java.io.IOException;
import java.io.Serializable;
-import java.nio.file.Files;
-import java.nio.file.Paths;
import java.util.Date;
import static org.dizitart.no2.filters.FluentFilter.where;
@@ -68,7 +65,7 @@ public void setUp() {
}
@After
- public void reset() throws IOException {
+ public void reset() {
(new NitriteConfig()).fieldSeparator(".");
if (db != null && !db.isClosed()) {
db.close();
@@ -79,7 +76,7 @@ public void reset() throws IOException {
db.close();
}
- Files.delete(Paths.get(fileName));
+ TestUtil.deleteDb(fileName);
}
@Test
diff --git a/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/FieldProcessorTest.java b/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/FieldProcessorTest.java
deleted file mode 100644
index ad53f1c91..000000000
--- a/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/FieldProcessorTest.java
+++ /dev/null
@@ -1,194 +0,0 @@
-/*
- * Copyright (c) 2017-2021 Nitrite author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package org.dizitart.no2.integration.repository;
-
-import org.dizitart.no2.collection.Document;
-import org.dizitart.no2.collection.NitriteId;
-import org.dizitart.no2.common.WriteResult;
-import org.dizitart.no2.common.crypto.AESEncryptor;
-import org.dizitart.no2.common.crypto.Encryptor;
-import org.dizitart.no2.common.processors.Processor;
-import org.dizitart.no2.common.processors.StringFieldEncryptionProcessor;
-import org.dizitart.no2.exceptions.NitriteSecurityException;
-import org.dizitart.no2.repository.ObjectRepository;
-import org.dizitart.no2.store.NitriteMap;
-import org.dizitart.no2.integration.repository.data.EncryptedPerson;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.nio.charset.StandardCharsets;
-import java.util.Date;
-import java.util.List;
-
-import static org.dizitart.no2.common.util.Iterables.toList;
-import static org.dizitart.no2.common.util.ObjectUtils.findRepositoryName;
-import static org.dizitart.no2.filters.FluentFilter.where;
-import static org.junit.Assert.*;
-
-/**
- * @author Anindya Chatterjee
- */
-public class FieldProcessorTest extends BaseObjectRepositoryTest {
- private ObjectRepository persons;
- private StringFieldEncryptionProcessor fieldProcessor;
-
- @Before
- public void setUp() {
- super.setUp();
- persons = db.getRepository(EncryptedPerson.class);
- fieldProcessor = new StringFieldEncryptionProcessor("s3k4e8");
- fieldProcessor.addFields("creditCardNumber", "cvv");
-
- EncryptedPerson person = new EncryptedPerson();
- person.setName("John Doe");
- person.setCreditCardNumber("5548960345687452");
- person.setCvv("007");
- person.setExpiryDate(new Date());
-
- persons.insert(person);
-
- // process existing data
- fieldProcessor.process(persons);
-
- // add for further changes
- persons.addProcessor(fieldProcessor);
-
- person = new EncryptedPerson();
- person.setName("Jane Doe");
- person.setCreditCardNumber("5500960345687452");
- person.setCvv("008");
- person.setExpiryDate(new Date());
- persons.insert(person);
- }
-
- @Test
- public void testFieldEncryptionInNitriteMap() {
- NitriteMap nitriteMap = persons.getDocumentCollection().getStore()
- .openMap(findRepositoryName(EncryptedPerson.class, null), NitriteId.class, Document.class);
-
- List documents = toList(nitriteMap.values());
- for (Document document : documents) {
- if (document.get("creditCardNumber", String.class).equalsIgnoreCase("5548960345687452")) {
- Assert.fail("unencrypted secret text found");
- }
-
- if (document.get("creditCardNumber", String.class).equalsIgnoreCase("5500960345687452")) {
- Assert.fail("unencrypted secret text found");
- }
-
- if (document.get("cvv", String.class).equalsIgnoreCase("008")) {
- Assert.fail("unencrypted secret text found");
- }
-
- if (document.get("cvv", String.class).equalsIgnoreCase("007")) {
- Assert.fail("unencrypted secret text found");
- }
- }
- }
-
- @Test
- public void testSuccessfulDecryption() {
- EncryptedPerson person = persons.find(where("name").eq("Jane Doe")).firstOrNull();
- assertNotNull(person);
-
- assertEquals(person.getCreditCardNumber(), "5500960345687452");
- assertEquals(person.getCvv(), "008");
-
- person = persons.find(where("name").eq("John Doe")).firstOrNull();
- assertNotNull(person);
-
- assertEquals(person.getCreditCardNumber(), "5548960345687452");
- assertEquals(person.getCvv(), "007");
- }
-
- @Test(expected = NitriteSecurityException.class)
- public void testFailedDecryption() {
- ObjectRepository testPersons = db.getRepository(EncryptedPerson.class, "test");
-
- Encryptor encryptor = new AESEncryptor("secret");
- Encryptor wrongEncryptor = new AESEncryptor("secret", "AES/GCM/NoPadding",
- 5, 5, 5);
-
- testPersons.addProcessor(new Processor() {
- @Override
- public Document processBeforeWrite(Document document) {
- String creditCardNumber = document.get("creditCardNumber", String.class);
- String encryptedCreditCardNumber = encryptor.encrypt(creditCardNumber.getBytes(StandardCharsets.UTF_8));
- document.put("creditCardNumber", encryptedCreditCardNumber);
- return document;
- }
-
- @Override
- public Document processAfterRead(Document document) {
- String encryptedCreditCardNumber = document.get("creditCardNumber", String.class);
- String creditCardNumber = wrongEncryptor.decrypt(encryptedCreditCardNumber);
- document.put("creditCardNumber", creditCardNumber);
- return document;
- }
- });
-
- EncryptedPerson person = new EncryptedPerson();
- person.setName("John Doe");
- person.setCreditCardNumber("5548960345687452");
- person.setCvv("007");
- person.setExpiryDate(new Date());
-
- testPersons.insert(person);
-
- person = new EncryptedPerson();
- person.setName("Jane Doe");
- person.setCreditCardNumber("5500960345687452");
- person.setCvv("008");
- person.setExpiryDate(new Date());
- testPersons.insert(person);
-
- testPersons.find(where("name").eq("Jane Doe")).firstOrNull();
- }
-
- @Test
- public void testSearchOnEncryptedField() {
- EncryptedPerson person = persons.find(where("cvv").eq("008")).firstOrNull();
- assertNull(person);
- }
-
- @Test
- public void testUpdateEncryptedField() {
- EncryptedPerson person = new EncryptedPerson();
- person.setName("John Doe");
- person.setCreditCardNumber("00000000000000");
- person.setCvv("007");
- person.setExpiryDate(new Date());
-
- WriteResult writeResult = persons.update(where("name").eq("John Doe"), person);
- assertEquals(writeResult.getAffectedCount(), 1);
-
- person = persons.find(where("name").eq("John Doe")).firstOrNull();
- assertNotNull(person);
-
- assertEquals(person.getCreditCardNumber(), "00000000000000");
- assertEquals(person.getCvv(), "007");
- }
-
- @Test
- public void testIndexOnEncryptedField() {
- persons.createIndex("cvv");
- EncryptedPerson person = persons.find(where("cvv").eq("008")).firstOrNull();
- assertNull(person);
- }
-}
diff --git a/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/JacksonModuleTest.java b/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/JacksonModuleTest.java
index b392f06e5..bad871a27 100644
--- a/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/JacksonModuleTest.java
+++ b/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/JacksonModuleTest.java
@@ -11,15 +11,13 @@
import org.junit.After;
import org.junit.Test;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Paths;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.UUID;
import static org.dizitart.no2.integration.repository.BaseObjectRepositoryTest.getRandomTempDbFile;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
/**
* @author Anindya Chatterjee
@@ -29,11 +27,11 @@ public class JacksonModuleTest {
private final String fileName = getRandomTempDbFile();
@After
- public void cleanUp() throws IOException {
+ public void cleanUp() {
if (db != null && !db.isClosed()) {
db.close();
}
- Files.delete(Paths.get(fileName));
+ TestUtil.deleteDb(fileName);
}
@Test(expected = ObjectMappingException.class)
@@ -60,7 +58,7 @@ public void testJavaTime() {
assertEquals(repository.find().size(), 10);
for (TestData testData : repository.find()) {
- System.out.println(testData.localDateTime);
+ assertNotNull(testData.localDateTime);
}
}
@@ -88,7 +86,7 @@ public void testJavaTimeModule() {
assertEquals(repository.find().size(), 10);
for (TestData testData : repository.find()) {
- System.out.println(testData.localDateTime);
+ assertNotNull(testData.localDateTime);
}
}
diff --git a/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/NitriteIdAsIdTest.java b/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/NitriteIdAsIdTest.java
index 4296bcdcf..096e9a82b 100644
--- a/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/NitriteIdAsIdTest.java
+++ b/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/NitriteIdAsIdTest.java
@@ -21,9 +21,9 @@
import org.dizitart.no2.Nitrite;
import org.dizitart.no2.collection.NitriteId;
import org.dizitart.no2.common.WriteResult;
+import org.dizitart.no2.common.mapper.JacksonMapper;
import org.dizitart.no2.common.util.Iterables;
import org.dizitart.no2.exceptions.InvalidIdException;
-import org.dizitart.no2.common.mapper.JacksonMapper;
import org.dizitart.no2.repository.Cursor;
import org.dizitart.no2.repository.ObjectRepository;
import org.dizitart.no2.repository.annotations.Id;
@@ -32,10 +32,6 @@
import org.junit.Rule;
import org.junit.Test;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Paths;
-
import static org.dizitart.no2.common.module.NitriteModule.module;
import static org.dizitart.no2.integration.repository.BaseObjectRepositoryTest.getRandomTempDbFile;
import static org.dizitart.no2.integration.repository.TestUtil.createDb;
@@ -61,9 +57,9 @@ public void before() {
}
@After
- public void after() throws IOException {
+ public void after() {
db.close();
- Files.delete(Paths.get(fileName));
+ TestUtil.deleteDb(fileName);
}
@Test
@@ -78,7 +74,6 @@ public void testNitriteIdField() {
Cursor cursor = repo.find();
for (WithNitriteId withNitriteId : cursor) {
- System.out.println(withNitriteId.name);
assertNotNull(withNitriteId.idField);
}
diff --git a/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/ObjectCursorTest.java b/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/ObjectCursorTest.java
index 4f9aa507c..bb8c8a728 100644
--- a/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/ObjectCursorTest.java
+++ b/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/ObjectCursorTest.java
@@ -21,6 +21,7 @@
import org.dizitart.no2.exceptions.ValidationException;
import org.dizitart.no2.integration.repository.data.Employee;
import org.dizitart.no2.repository.Cursor;
+import org.junit.Assert;
import org.junit.Test;
import java.util.AbstractCollection;
@@ -59,6 +60,6 @@ public void testProjectForAbstractClass() {
public void testProjectForValueType() {
Cursor cursor = employeeRepository.find();
RecordStream project = cursor.project(Date.class);
- project.forEach(System.out::println);
+ project.forEach(Assert::assertNotNull);
}
}
diff --git a/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/ObjectRepositoryNegativeTest.java b/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/ObjectRepositoryNegativeTest.java
index 178d688ee..281c02d08 100644
--- a/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/ObjectRepositoryNegativeTest.java
+++ b/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/ObjectRepositoryNegativeTest.java
@@ -30,10 +30,6 @@
import org.junit.Rule;
import org.junit.Test;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Paths;
-
import static org.junit.Assert.*;
/**
@@ -52,10 +48,10 @@ public void setUp() {
}
@After
- public void close() throws IOException {
+ public void close() {
db.close();
db = null;
- Files.delete(Paths.get(dbPath));
+ TestUtil.deleteDb(dbPath);
}
@Test(expected = ObjectMappingException.class)
diff --git a/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/ObjectRepositoryTest.java b/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/ObjectRepositoryTest.java
index e0a510606..f829b4050 100644
--- a/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/ObjectRepositoryTest.java
+++ b/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/ObjectRepositoryTest.java
@@ -21,8 +21,8 @@
import lombok.Data;
import org.dizitart.no2.Nitrite;
import org.dizitart.no2.collection.NitriteCollection;
-import org.dizitart.no2.common.meta.Attributes;
import org.dizitart.no2.common.mapper.JacksonMapperModule;
+import org.dizitart.no2.common.meta.Attributes;
import org.dizitart.no2.exceptions.ValidationException;
import org.dizitart.no2.index.IndexType;
import org.dizitart.no2.integration.repository.data.*;
@@ -36,9 +36,6 @@
import org.junit.Rule;
import org.junit.Test;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Paths;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@@ -64,10 +61,10 @@ public void setUp() {
}
@After
- public void close() throws IOException {
+ public void close() {
db.close();
db = null;
- Files.delete(Paths.get(dbPath));
+ TestUtil.deleteDb(dbPath);
}
@Test
diff --git a/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/RepositoryJoinTest.java b/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/RepositoryJoinTest.java
index ccd66e1dd..6e1556eb4 100644
--- a/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/RepositoryJoinTest.java
+++ b/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/RepositoryJoinTest.java
@@ -24,8 +24,8 @@
import org.dizitart.no2.collection.NitriteId;
import org.dizitart.no2.common.Lookup;
import org.dizitart.no2.common.RecordStream;
-import org.dizitart.no2.exceptions.InvalidOperationException;
import org.dizitart.no2.common.mapper.JacksonMapperModule;
+import org.dizitart.no2.exceptions.InvalidOperationException;
import org.dizitart.no2.mvstore.MVStoreModule;
import org.dizitart.no2.mvstore.MVStoreModuleBuilder;
import org.dizitart.no2.repository.ObjectRepository;
@@ -38,8 +38,6 @@
import org.junit.runners.Parameterized;
import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
@@ -166,7 +164,7 @@ public void clear() throws IOException {
}
if (!inMemory) {
- Files.delete(Paths.get(fileName));
+ TestUtil.deleteDb(fileName);
}
}
diff --git a/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/RepositorySearchTest.java b/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/RepositorySearchTest.java
index 47ef2fbb6..b582b49d2 100644
--- a/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/RepositorySearchTest.java
+++ b/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/RepositorySearchTest.java
@@ -61,8 +61,8 @@ public void testEmployeeProjection() {
assertNotNull(employeeList);
assertNotNull(subEmployeeList);
- assertTrue(employeeList.size() > 0);
- assertTrue(subEmployeeList.size() > 0);
+ assertFalse(employeeList.isEmpty());
+ assertFalse(subEmployeeList.isEmpty());
assertEquals(employeeList.size(), subEmployeeList.size());
diff --git a/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/Retry.java b/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/Retry.java
index 7c2c065bd..475106b6e 100644
--- a/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/Retry.java
+++ b/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/Retry.java
@@ -17,6 +17,7 @@
package org.dizitart.no2.integration.repository;
+import lombok.extern.slf4j.Slf4j;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
@@ -24,6 +25,7 @@
/**
* @author Anindya Chatterjee
*/
+@Slf4j
public class Retry implements TestRule {
private final int retryCount;
@@ -48,11 +50,13 @@ public void evaluate() throws Throwable {
return;
} catch (Throwable t) {
caughtThrowable = t;
- System.err.println(description.getDisplayName() + ": run " + (i + 1) + " failed");
+ log.warn(description.getDisplayName() + ": run " + (i + 1) + " failed");
}
}
- System.err.println(description.getDisplayName() + ": giving up after " + retryCount + " failures");
- throw caughtThrowable;
+ log.error(description.getDisplayName() + ": giving up after " + retryCount + " failures");
+ if (caughtThrowable != null) {
+ throw caughtThrowable;
+ }
}
};
}
diff --git a/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/TestUtil.java b/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/TestUtil.java
index 6967e6289..264b53b6f 100644
--- a/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/TestUtil.java
+++ b/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/TestUtil.java
@@ -22,6 +22,9 @@
import org.dizitart.no2.common.module.NitriteModule;
import org.dizitart.no2.mvstore.MVStoreModule;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+
/**
* @author Anindya Chatterjee
*/
@@ -70,4 +73,12 @@ public static Nitrite createDb(String filePath, String user, String password, Ni
.fieldSeparator(".")
.openOrCreate(user, password);
}
+
+ public static void deleteDb(String filePath) {
+ try {
+ Files.delete(Paths.get(filePath));
+ } catch (Exception e) {
+ log.error("Error while deleting db", e);
+ }
+ }
}
diff --git a/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/UnAnnotatedObjectTest.java b/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/UnAnnotatedObjectTest.java
index 734a55e29..0306f8eca 100644
--- a/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/UnAnnotatedObjectTest.java
+++ b/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/UnAnnotatedObjectTest.java
@@ -25,8 +25,7 @@
import static org.dizitart.no2.collection.FindOptions.orderBy;
import static org.dizitart.no2.filters.FluentFilter.where;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.*;
/**
* @author Anindya Chatterjee.
@@ -44,33 +43,25 @@ public void testFind() {
cursor = aObjectRepository.find(where("b.number").eq(160).not(),
orderBy("b.number", SortOrder.Ascending).skip(0).limit(10));
- System.out.println("Available - " + !cursor.isEmpty());
- System.out.println("Total Size - " + cursor.size());
-
Iterable findRecord = cursor.project(ClassA.class);
for (ClassA classA : findRecord) {
- System.out.println(classA);
+ assertNotNull(classA);
}
cursor = aObjectRepository.find(where("b.number").eq(160).not(),
orderBy("b.number", SortOrder.Descending).skip(2).limit(7));
- System.out.println("Available - " + !cursor.isEmpty());
- System.out.println("Total Size - " + cursor.size());
-
findRecord = cursor.project(ClassA.class);
for (ClassA classA : findRecord) {
- System.out.println(classA);
+ assertNotNull(classA);
}
cursor = cObjectRepository.find(where("id").gt(900),
orderBy("id", SortOrder.Descending).skip(2).limit(7));
- System.out.println("Available - " + !cursor.isEmpty());
- System.out.println("Total Size - " + cursor.size());
Iterable findRecordC = cursor.project(ClassC.class);
for (ClassC classC : findRecordC) {
- System.out.println(classC);
+ assertNotNull(classC);
}
}
}
diff --git a/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/UniversalTextTokenizerTest.java b/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/UniversalTextTokenizerTest.java
index 566dc82b0..e92fa2848 100644
--- a/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/UniversalTextTokenizerTest.java
+++ b/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/repository/UniversalTextTokenizerTest.java
@@ -34,9 +34,6 @@
import org.junit.Before;
import org.junit.Test;
-import java.nio.file.Files;
-import java.nio.file.Paths;
-
import static org.dizitart.no2.common.module.NitriteModule.module;
import static org.dizitart.no2.filters.Filter.ALL;
import static org.dizitart.no2.filters.FluentFilter.where;
@@ -93,7 +90,7 @@ public void clear() throws Exception {
}
if (!inMemory) {
- Files.delete(Paths.get(fileName));
+ TestUtil.deleteDb(fileName);
}
}
@@ -139,7 +136,6 @@ public void testUniversalFullTextIndexing() {
Cursor cursor = textRepository.find(where("text").text("Lorem"));
assertEquals(cursor.size(), 2);
for (TextData data : cursor) {
- System.out.println("Id for English text -> " + data.id);
if (data.id % 2 == 0 || data.id % 3 == 0 || data.id % 5 == 0) {
fail();
}
@@ -148,7 +144,6 @@ public void testUniversalFullTextIndexing() {
cursor = textRepository.find(where("text").text("শহর"));
assertEquals(cursor.size(), 5);
for (TextData data : cursor) {
- System.out.println("Id for Bengali text -> " + data.id);
if (data.id % 2 != 0) {
fail();
}
@@ -159,7 +154,6 @@ public void testUniversalFullTextIndexing() {
cursor = textRepository.find(where("text").text("*転閉*"));
assertEquals(cursor.size(), 2);
for (TextData data : cursor) {
- System.out.println("Id for Chinese text -> " + data.id);
if (data.id % 3 != 0) {
fail();
}
@@ -169,7 +163,6 @@ public void testUniversalFullTextIndexing() {
if (isCompressed) {
assertEquals(cursor.size(), 1);
for (TextData data : cursor) {
- System.out.println("Id for Arabic text -> " + data.id);
if (data.id % 5 != 0) {
fail();
}
diff --git a/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/transaction/TransactionRepositoryTest.java b/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/transaction/TransactionRepositoryTest.java
index 4adab1075..7d3c1ff00 100644
--- a/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/transaction/TransactionRepositoryTest.java
+++ b/nitrite-jackson-mapper/src/test/java/org/dizitart/no2/integration/transaction/TransactionRepositoryTest.java
@@ -18,6 +18,7 @@
package org.dizitart.no2.integration.transaction;
import com.github.javafaker.Faker;
+import lombok.extern.slf4j.Slf4j;
import org.dizitart.no2.collection.Document;
import org.dizitart.no2.collection.NitriteCollection;
import org.dizitart.no2.common.meta.Attributes;
@@ -45,6 +46,7 @@
/**
* @author Anindya Chatterjee
*/
+@Slf4j
public class TransactionRepositoryTest extends BaseObjectRepositoryTest {
@Test
@@ -588,7 +590,7 @@ public void testConcurrentInsertAndRemove() {
transaction.commit();
} catch (Exception e) {
- e.printStackTrace();
+ log.error("Error while inserting", e);
transaction.rollback();
} finally {
transaction.close();
@@ -602,7 +604,7 @@ public void testConcurrentInsertAndRemove() {
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
- e.printStackTrace();
+ log.error("Error while inserting", e);
}
});
@@ -632,7 +634,7 @@ public void testConcurrentInsert() {
transaction.commit();
} catch (Exception e) {
- e.printStackTrace();
+ log.error("Error while inserting", e);
transaction.rollback();
} finally {
transaction.close();
@@ -646,7 +648,7 @@ public void testConcurrentInsert() {
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
- e.printStackTrace();
+ log.error("Error while inserting", e);
}
});
@@ -679,7 +681,7 @@ public void testConcurrentUpdate() {
transaction.commit();
} catch (Exception e) {
- e.printStackTrace();
+ log.error("Error while updating", e);
transaction.rollback();
} finally {
transaction.close();
@@ -693,7 +695,7 @@ public void testConcurrentUpdate() {
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
- e.printStackTrace();
+ log.error("Error while updating", e);
}
});
diff --git a/nitrite-mvstore-adapter/pom.xml b/nitrite-mvstore-adapter/pom.xml
index 4b060ed73..0a9d0a21a 100644
--- a/nitrite-mvstore-adapter/pom.xml
+++ b/nitrite-mvstore-adapter/pom.xml
@@ -151,6 +151,19 @@
org.apache.maven.plugins
maven-javadoc-plugin
+
+
+ org.dizitart.no2.mvstore.compat.v1,
+
+
+ **/*MVSpatialKey.java
+ **/*MVStoreUtils.java
+ **/*NitriteMVMap.java
+ **/*NitriteMVRTreeMap.java
+ **/*NitriteMVStore.java
+ **/*ReverseIterator.java
+
+
org.apache.maven.plugins
diff --git a/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/MVSpatialKey.java b/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/MVSpatialKey.java
index c7fc552b1..f41490173 100644
--- a/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/MVSpatialKey.java
+++ b/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/MVSpatialKey.java
@@ -23,6 +23,7 @@
import java.util.Arrays;
/**
+ * @since 4.0
* @author Anindya Chatterjee
*/
public class MVSpatialKey extends SpatialKey implements Spatial {
diff --git a/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/MVStoreConfig.java b/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/MVStoreConfig.java
index a51bfab7c..cbfc94d9a 100644
--- a/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/MVStoreConfig.java
+++ b/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/MVStoreConfig.java
@@ -16,7 +16,6 @@
package org.dizitart.no2.mvstore;
-
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
@@ -29,54 +28,97 @@
import java.util.Set;
/**
- * Represents MV store configuration
- *
- * @since 4.0.0
+ * Configuration class for MVStore.
+ *
+ * @since 4.0
* @author Anindya Chatterjee
*/
@Getter
@Accessors(fluent = true)
public class MVStoreConfig implements StoreConfig {
@Setter(AccessLevel.PACKAGE)
+ /**
+ * The set of event listeners for the MVStore.
+ */
private Set eventListeners;
@Setter(AccessLevel.PACKAGE)
+ /**
+ * The file path of the MVStore file.
+ */
private String filePath;
@Setter(AccessLevel.PACKAGE)
+ /**
+ * The size of the buffer used for auto-commit operations.
+ */
private int autoCommitBufferSize;
@Setter(AccessLevel.PACKAGE)
+ /**
+ * The encryption key to be used for encrypting and decrypting the data.
+ */
private char[] encryptionKey;
@Setter(AccessLevel.PACKAGE)
+ /**
+ * A flag indicating whether the MVStore should be opened in read-only mode.
+ */
private Boolean isReadOnly = false;
@Setter(AccessLevel.PACKAGE)
+ /**
+ * Indicates whether the MVStore should compress data or not.
+ */
private boolean compress;
@Setter(AccessLevel.PACKAGE)
+ /**
+ * Indicates whether to use high compression for data blocks.
+ */
private boolean compressHigh;
@Setter(AccessLevel.PACKAGE)
+ /**
+ * Indicates whether auto-commit mode is enabled for the MVStore.
+ */
private boolean autoCommit;
@Setter(AccessLevel.PACKAGE)
+ /**
+ * Sets a value indicating whether the MVStore should automatically compact
+ * itself when it is closed.
+ */
private boolean autoCompact;
@Setter(AccessLevel.PACKAGE)
+ /**
+ * Indicates whether the MVStore should be opened in recovery mode or not.
+ */
private boolean recoveryMode;
@Setter(AccessLevel.PACKAGE)
+ /**
+ * The size of the cache (in KB) used by the MVStore.
+ */
private int cacheSize;
@Setter(AccessLevel.PACKAGE)
+ /**
+ * The number of threads that can concurrently access the MVStore cache.
+ */
private int cacheConcurrency;
+ /**
+ * Sets the page split size for the MVStore.
+ */
@Setter(AccessLevel.PACKAGE)
private int pageSplitSize;
@Setter(AccessLevel.PACKAGE)
+ /**
+ * The file store used by the MVStore.
+ */
private FileStore> fileStore;
MVStoreConfig() {
@@ -88,6 +130,11 @@ public void addStoreEventListener(StoreEventListener listener) {
eventListeners.add(listener);
}
+ /**
+ * Creates and returns a copy of this object.
+ *
+ * @return a clone of this instance.
+ */
public MVStoreConfig clone() {
MVStoreConfig config = new MVStoreConfig();
config.eventListeners(new HashSet<>(eventListeners));
diff --git a/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/MVStoreModule.java b/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/MVStoreModule.java
index dc72c0d22..d716f36ed 100644
--- a/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/MVStoreModule.java
+++ b/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/MVStoreModule.java
@@ -18,7 +18,6 @@
import lombok.AccessLevel;
import lombok.Setter;
-import org.dizitart.no2.common.module.NitriteModule;
import org.dizitart.no2.common.module.NitritePlugin;
import org.dizitart.no2.store.NitriteStore;
import org.dizitart.no2.store.StoreModule;
@@ -28,15 +27,24 @@
import static org.dizitart.no2.common.util.Iterables.setOf;
/**
- * A {@link NitriteModule} which provides h2's mvstore as a storage engine.
- *
- * @since 4.0.0
+ * A Nitrite module that provides a Nitrite store implementation using H2 MVStore.
+ *
+ * @since 4.0
+ * @see NitriteStore
* @author Anindya Chatterjee
*/
public class MVStoreModule implements StoreModule {
@Setter(AccessLevel.PACKAGE)
+ /**
+ * The configuration object for the MVStore.
+ */
private MVStoreConfig storeConfig;
+ /**
+ * Constructs a new instance of {@link MVStoreModule} with the specified file path.
+ *
+ * @param path the file path for the MVStore database.
+ */
public MVStoreModule(String path) {
this.storeConfig = new MVStoreConfig();
this.storeConfig.filePath(path);
@@ -47,10 +55,20 @@ public Set plugins() {
return setOf(getStore());
}
+ /**
+ * Returns a new instance of {@link MVStoreModuleBuilder} to configure the MVStore module.
+ *
+ * @return a new instance of {@link MVStoreModuleBuilder}.
+ */
public static MVStoreModuleBuilder withConfig() {
return new MVStoreModuleBuilder();
}
+ /**
+ * Returns a new instance of {@link NitriteStore} with the configured {@link StoreConfig}.
+ *
+ * @return a new instance of {@link NitriteStore}.
+ */
public NitriteStore> getStore() {
NitriteMVStore store = new NitriteMVStore();
store.setStoreConfig(storeConfig);
diff --git a/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/MVStoreModuleBuilder.java b/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/MVStoreModuleBuilder.java
index 2fab152cf..215ffbe2c 100644
--- a/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/MVStoreModuleBuilder.java
+++ b/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/MVStoreModuleBuilder.java
@@ -28,27 +28,95 @@
import java.util.Set;
/**
+ * The MVStoreModuleBuilder class is responsible for building an instance of
+ * {@link MVStoreModule}. It provides methods to set various configuration
+ * options for the MVStore database.
+ *
+ * @since 4.0
+ * @see MVStoreModule
* @author Anindya Chatterjee
*/
@Getter
@Setter
@Accessors(fluent = true)
public class MVStoreModuleBuilder {
+ /**
+ * The file path of the MVStore file.
+ */
private String filePath;
+
+ /**
+ * The size of the buffer used for auto-commit. When the buffer is full,
+ * the changes are automatically committed to the database. The default
+ * buffer size is 1024.
+ */
private int autoCommitBufferSize = 1024;
+
+ /**
+ * The encryption key to be used for encrypting the MVStore.
+ */
private char[] encryptionKey;
+
+ /**
+ * Indicates whether the MVStore instance should be opened in read-only mode.
+ */
private boolean readOnly;
+
+ /**
+ * Flag to enable/disable compression of data in MVStore.
+ */
private boolean compress;
+
+ /**
+ * Flag to enable high compression for the MVStore. If set to true, the MVStore
+ * will use a higher compression level, which may result in slower read and
+ * write performance but smaller file size on disk.
+ */
private boolean compressHigh;
+
+ /**
+ * Flag to enable/disable auto-commit mode. If set to true, all changes
+ * will be committed immediately. If set to false, changes will be buffered
+ * and committed when {@link org.dizitart.no2.Nitrite#commit()} is called.
+ */
private boolean autoCommit = true;
+
+ /**
+ * Indicates whether the MVStore should be opened in recovery mode or not.
+ */
private boolean recoveryMode = false;
+
+ /**
+ * The size of the read cache in MB used by the MVStore. The default value is
+ * 16MB.
+ */
private int cacheSize = 16;
+
+ /**
+ * The read cache concurrency used by MVStore. Default is 16 segments.
+ */
private int cacheConcurrency = 16;
+
+ /**
+ * The amount of memory a MVStore page should contain at most, in bytes,
+ * before it is split. The default is 16 KB.
+ */
private int pageSplitSize = 16;
+
+ /**
+ * The file store used by the MVStore.
+ */
private FileStore> fileStore;
+
+ /**
+ * The configuration for the MVStore.
+ */
private MVStoreConfig dbConfig;
@Setter(AccessLevel.NONE)
+ /**
+ * Set of event listeners to be registered with the MVStore.
+ */
private final Set eventListeners;
MVStoreModuleBuilder() {
@@ -56,6 +124,12 @@ public class MVStoreModuleBuilder {
eventListeners = new HashSet<>();
}
+ /**
+ * Sets the file path for the MVStore.
+ *
+ * @param file the file path for the MVStore.
+ * @return the MVStoreModuleBuilder instance.
+ */
public MVStoreModuleBuilder filePath(File file) {
if (file != null) {
this.filePath = file.getPath();
@@ -63,16 +137,33 @@ public MVStoreModuleBuilder filePath(File file) {
return this;
}
+ /**
+ * Sets the file path for the MVStore.
+ *
+ * @param path the file path for the MVStore.
+ * @return the MVStoreModuleBuilder instance.
+ */
public MVStoreModuleBuilder filePath(String path) {
this.filePath = path;
return this;
}
+ /**
+ * Adds a {@link StoreEventListener} to the module builder.
+ *
+ * @param listener the listener to be added
+ * @return the module builder instance
+ */
public MVStoreModuleBuilder addStoreEventListener(StoreEventListener listener) {
eventListeners.add(listener);
return this;
}
+ /**
+ * Builds an instance of {@link MVStoreModule} with the configured parameters.
+ *
+ * @return an instance of {@link MVStoreModule}.
+ */
public MVStoreModule build() {
MVStoreModule module = new MVStoreModule(filePath());
diff --git a/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/MVStoreUtils.java b/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/MVStoreUtils.java
index 025e1f373..93cd5f56a 100644
--- a/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/MVStoreUtils.java
+++ b/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/MVStoreUtils.java
@@ -33,9 +33,9 @@
/**
* @author Anindya Chatterjee.
- * @since 4.0.0
+ * @since 4.0
*/
-@Slf4j
+@Slf4j(topic = "nitrite-mvstore")
@SuppressWarnings("ALL")
class MVStoreUtils {
private MVStoreUtils() {
@@ -98,7 +98,6 @@ static MVStore openOrCreate(MVStoreConfig storeConfig) {
if (store != null) {
store.setRetentionTime(0);
store.setVersionsToKeep(0);
-// store.setReuseSpace(true);
}
}
@@ -180,7 +179,7 @@ private static MVStore tryUpgrade(File orgFile, MVStoreConfig storeConfig) {
try {
UpgradeUtil.tryUpgrade(newBuilder, storeConfig);
} catch (Exception e) {
- // if the update fails, delete te new file and rethrow the exception
+ // if the update fails, delete the new file and rethrow the exception
if (newFile.exists()) {
if (!newFile.delete()) {
throw new NitriteIOException("Could not upgrade the data file", e);
diff --git a/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/Recovery.java b/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/Recovery.java
index 591b4a6c0..a79273435 100644
--- a/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/Recovery.java
+++ b/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/Recovery.java
@@ -16,13 +16,9 @@
package org.dizitart.no2.mvstore;
-import lombok.extern.slf4j.Slf4j;
import org.dizitart.no2.exceptions.NitriteIOException;
-import org.h2.mvstore.MVStoreTool;
import org.h2.store.fs.FilePath;
-import java.io.IOException;
-import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
@@ -30,12 +26,12 @@
import static org.h2.mvstore.MVStoreTool.rollback;
/**
- * The nitrite database recovery utility.
+ * The Recovery class provides methods to attempt a MVStore file recovery
+ * by rolling back to the newest good version.
*
* @author Anindya Chatterjee
* @since 1.0
*/
-@Slf4j
public class Recovery {
/**
diff --git a/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/ReverseIterator.java b/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/ReverseIterator.java
index f98c0fae0..033b2e847 100644
--- a/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/ReverseIterator.java
+++ b/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/ReverseIterator.java
@@ -7,6 +7,7 @@
import java.util.NoSuchElementException;
/**
+ * @since 4.0
* @author Anindya Chatterjee
*/
public class ReverseIterator implements Iterator> {
diff --git a/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/compat/v1/Compat.java b/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/compat/v1/Compat.java
index 4f8576621..4ccb102fc 100644
--- a/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/compat/v1/Compat.java
+++ b/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/compat/v1/Compat.java
@@ -23,48 +23,25 @@
import java.util.concurrent.atomic.AtomicBoolean;
/**
- * Nitrite v3 compatible classes used in data migration.
- *
* @author Anindya Chatterjee
- * @since 4.0.0
+ * @since 4.0
*/
class Compat {
- /**
- * The enum Index type.
- */
enum IndexType {
- /**
- * Unique index type.
- */
Unique,
- /**
- * Non unique index type.
- */
NonUnique,
- /**
- * Fulltext index type.
- */
Fulltext
}
- /**
- * The type User credential.
- */
@Data
static class UserCredential implements Serializable {
private byte[] passwordHash;
private byte[] passwordSalt;
}
- /**
- * The type Document.
- */
- static class Document extends LinkedHashMap implements Serializable {
+ static class Document extends LinkedHashMap {
}
- /**
- * The type Index.
- */
@Data
static class Index implements Serializable {
private IndexType indexType;
@@ -72,9 +49,6 @@ static class Index implements Serializable {
private String collectionName;
}
- /**
- * The type Index meta.
- */
@Data
static class IndexMeta implements Serializable {
private Index index;
@@ -82,9 +56,6 @@ static class IndexMeta implements Serializable {
private AtomicBoolean isDirty;
}
- /**
- * The type Attributes.
- */
@Data
static class Attributes implements Serializable {
private long createdTime;
@@ -96,9 +67,6 @@ static class Attributes implements Serializable {
private String uuid;
}
- /**
- * The type Nitrite id.
- */
@Data
static class NitriteId implements Serializable, Comparable {
private Long idValue;
diff --git a/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/compat/v1/MVMapBuilder.java b/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/compat/v1/MVMapBuilder.java
index 8f376e7d5..e5ef709c4 100644
--- a/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/compat/v1/MVMapBuilder.java
+++ b/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/compat/v1/MVMapBuilder.java
@@ -20,18 +20,11 @@
import org.dizitart.no2.mvstore.compat.v1.mvstore.MVMap;
/**
- * The type Mv map builder.
- *
- * @param the type parameter
- * @param the type parameter
- *
- * @since 4.0.0
+ * @since 4.0
* @author Anindya Chatterjee.
*/
class MVMapBuilder extends MVMap.Builder {
- /**
- * Instantiates a new Mv map builder.
- */
+
public MVMapBuilder() {
setKeyType(new NitriteDataType());
setValueType(new NitriteDataType());
diff --git a/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/compat/v1/NitriteDataType.java b/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/compat/v1/NitriteDataType.java
index b4932cd05..bf05c3199 100644
--- a/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/compat/v1/NitriteDataType.java
+++ b/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/compat/v1/NitriteDataType.java
@@ -37,10 +37,7 @@
import java.util.UUID;
/**
- * The type Nitrite data type.
- *
- * NOTE: This code is a modification of h2 mvstore's {@link ObjectDataType}
- * @since 4.0.0
+ * @since 4.0
* @author H2 Group
* @author Anindya Chatterjee
*/
diff --git a/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/compat/v1/NitriteObjectInputStream.java b/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/compat/v1/NitriteObjectInputStream.java
index d04a328f3..86313cecc 100644
--- a/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/compat/v1/NitriteObjectInputStream.java
+++ b/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/compat/v1/NitriteObjectInputStream.java
@@ -26,12 +26,10 @@
import java.util.Map;
/**
- * A specialized version of {@link ObjectInputStream} for nitrite.
- *
- * @since 4.0.0
+ * @since 4.0
* @author Anindya Chatterjee.
*/
-@Slf4j
+@Slf4j(topic = "nitrite-mvstore")
class NitriteObjectInputStream extends ObjectInputStream {
private static final Map> migrationMap = new HashMap<>();
diff --git a/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/compat/v1/UpgradeUtil.java b/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/compat/v1/UpgradeUtil.java
index 3d3db1743..f43687e0c 100644
--- a/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/compat/v1/UpgradeUtil.java
+++ b/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/compat/v1/UpgradeUtil.java
@@ -44,9 +44,10 @@
import static org.dizitart.no2.common.util.StringUtils.isNullOrEmpty;
/**
+ * @since 4.0
* @author Anindya Chatterjee
*/
-@Slf4j
+@Slf4j(topic = "nitrite-mvstore")
public class UpgradeUtil {
private UpgradeUtil() {
}
diff --git a/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/compat/v1/mvstore/compress/CompressLZF.java b/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/compat/v1/mvstore/compress/CompressLZF.java
index 62d0adae7..b66ddd25d 100644
--- a/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/compat/v1/mvstore/compress/CompressLZF.java
+++ b/nitrite-mvstore-adapter/src/main/java/org/dizitart/no2/mvstore/compat/v1/mvstore/compress/CompressLZF.java
@@ -9,10 +9,6 @@
import java.nio.ByteBuffer;
public final class CompressLZF implements Compressor {
- private static final int HASH_SIZE = 16384;
- private static final int MAX_LITERAL = 32;
- private static final int MAX_OFF = 8192;
- private static final int MAX_REF = 264;
private int[] cachedHashTable;
public CompressLZF() {
diff --git a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/NitriteTest.java b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/NitriteTest.java
index 2e1a0e15c..6e27e27c8 100644
--- a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/NitriteTest.java
+++ b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/NitriteTest.java
@@ -20,16 +20,16 @@
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
import org.dizitart.no2.collection.Document;
import org.dizitart.no2.collection.FindOptions;
import org.dizitart.no2.collection.NitriteCollection;
import org.dizitart.no2.collection.UpdateOptions;
import org.dizitart.no2.common.SortOrder;
-import org.dizitart.no2.common.WriteResult;
import org.dizitart.no2.common.concurrent.ThreadPoolManager;
import org.dizitart.no2.common.mapper.EntityConverter;
+import org.dizitart.no2.common.mapper.SimpleNitriteMapper;
import org.dizitart.no2.common.mapper.NitriteMapper;
-import org.dizitart.no2.common.mapper.SimpleDocumentMapper;
import org.dizitart.no2.exceptions.NitriteIOException;
import org.dizitart.no2.exceptions.ValidationException;
import org.dizitart.no2.index.IndexOptions;
@@ -73,6 +73,7 @@
/**
* @author Anindya Chatterjee.
*/
+@Slf4j
public class NitriteTest {
private Nitrite db;
private NitriteCollection collection;
@@ -86,7 +87,7 @@ public class NitriteTest {
public void setUp() throws ParseException {
db = TestUtil.createDb(fileName, "test-user", "test-password");
- SimpleDocumentMapper documentMapper = (SimpleDocumentMapper) db.getConfig().nitriteMapper();
+ SimpleNitriteMapper documentMapper = (SimpleNitriteMapper) db.getConfig().nitriteMapper();
documentMapper.registerEntityConverter(new CompatChild.Converter());
documentMapper.registerEntityConverter(new Receipt.Converter());
documentMapper.registerEntityConverter(new EmptyClass.Converter());
@@ -379,7 +380,7 @@ public void testIssue185() throws InterruptedException {
} catch (InterruptedException ignored) {
}
} catch (Throwable t) {
- t.printStackTrace();
+ log.error("Error in thread", t);
}
}
latch.countDown();
@@ -491,7 +492,7 @@ public void testReadCompatibility() throws IOException {
String oldDbFile = System.getProperty("java.io.tmpdir") + File.separator + "old.db";
Nitrite db = TestUtil.createDb(oldDbFile, "test-user", "test-password");
- SimpleDocumentMapper documentMapper = (SimpleDocumentMapper) db.getConfig().nitriteMapper();
+ SimpleNitriteMapper documentMapper = (SimpleNitriteMapper) db.getConfig().nitriteMapper();
documentMapper.registerEntityConverter(new Receipt.Converter());
NitriteCollection collection = db.getCollection("test");
@@ -537,7 +538,7 @@ public void testIssue212() {
doc, UpdateOptions.updateOptions(true));
for (Document document : collection.find()) {
- System.out.println(document);
+ assertNotNull(document);
}
}
@@ -551,13 +552,8 @@ public void run() {
NitriteCollection collection = db.getCollection("testIssue245");
for (int i = 0; i < 5; i++) {
-
- System.out.println("Thread ID = " + id + " Inserting doc " + i);
Document doc = Document.createDocument(UUID.randomUUID().toString(), UUID.randomUUID().toString());
-
- WriteResult result = collection.insert(doc);//db.commit();
- System.out.println("Result of insert = " + result.getAffectedCount());
- System.out.println("Thread id = " + id + " --> count = " + collection.size());
+ collection.insert(doc);//db.commit();
Thread.sleep(10);
@@ -566,7 +562,7 @@ public void run() {
collection.close();
} catch (Exception e) {
- e.printStackTrace();
+ log.error("Error in thread", e);
}
}
};
@@ -586,7 +582,6 @@ public void run() {
t2.join();
NitriteCollection collection = db.getCollection("testIssue245");
- System.out.println("No of Documents = " + collection.size());
collection.close();
db.close();
}
diff --git a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/MultiThreadedTest.java b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/MultiThreadedTest.java
index 11a7b35bf..a189a76a1 100644
--- a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/MultiThreadedTest.java
+++ b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/MultiThreadedTest.java
@@ -17,6 +17,7 @@
package org.dizitart.no2.integration;
+import lombok.extern.slf4j.Slf4j;
import org.dizitart.no2.Nitrite;
import org.dizitart.no2.collection.Document;
import org.dizitart.no2.collection.DocumentCursor;
@@ -47,6 +48,7 @@
/**
* @author Anindya Chatterjee.
*/
+@Slf4j
@RunWith(Parameterized.class)
public class MultiThreadedTest {
private static final String fileName = TestUtil.getRandomTempDbFile();
@@ -112,9 +114,7 @@ public void testOperations() throws InterruptedException {
assertTrue(collection.hasIndex("unixTime"));
} catch (Throwable e) {
- System.out.println("Exception at thread " +
- Thread.currentThread().getName() + " with iteration " + j);
- e.printStackTrace();
+ log.error("Error while executing test", e);
}
}
latch.countDown();
@@ -147,7 +147,7 @@ public void cleanUp() throws Exception {
File dbFile = new File(fileName);
long fileSize = dbFile.length();
assertTrue(fileSize > 0);
- dbFile.delete();
+ TestUtil.deleteDb(fileName);
}
if (executor != null && !executor.isShutdown()) {
diff --git a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/NitriteBuilderTest.java b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/NitriteBuilderTest.java
index 810ce1edd..f49a6088f 100644
--- a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/NitriteBuilderTest.java
+++ b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/NitriteBuilderTest.java
@@ -28,7 +28,7 @@
import org.dizitart.no2.common.Fields;
import org.dizitart.no2.common.mapper.EntityConverter;
import org.dizitart.no2.common.mapper.NitriteMapper;
-import org.dizitart.no2.common.mapper.SimpleDocumentMapper;
+import org.dizitart.no2.common.mapper.SimpleNitriteMapper;
import org.dizitart.no2.exceptions.InvalidOperationException;
import org.dizitart.no2.exceptions.NitriteIOException;
import org.dizitart.no2.exceptions.NitriteSecurityException;
@@ -80,7 +80,7 @@ public void startup() {
}
@After
- public void cleanup() throws IOException {
+ public void cleanup() {
(new NitriteConfig()).fieldSeparator(".");
if (db != null && !db.isClosed()) {
@@ -88,7 +88,7 @@ public void cleanup() throws IOException {
}
if (Files.exists(Paths.get(filePath))) {
- Files.delete(Paths.get(filePath));
+ TestUtil.deleteDb(filePath);
}
if (fakeDb != null && !fakeDb.isClosed()){
@@ -96,7 +96,7 @@ public void cleanup() throws IOException {
}
if (Files.exists(Paths.get(fakeFile))) {
- Files.delete(Paths.get(fakeFile));
+ TestUtil.deleteDb(fakeFile);
}
}
@@ -137,7 +137,7 @@ public void testConfig() throws IOException {
assertTrue(storeConfig.isReadOnly());
db.close();
- Files.delete(Paths.get(filePath));
+ TestUtil.deleteDb(filePath);
}
@Test
@@ -162,7 +162,7 @@ public void testConfigWithFile() {
db.commit();
db.close();
- assertTrue(file.delete());
+ TestUtil.deleteDb(filePath);
}
@Test
@@ -194,7 +194,7 @@ public void testPopulateRepositories() {
.loadModule(module)
.openOrCreate();
- SimpleDocumentMapper documentMapper = (SimpleDocumentMapper) db.getConfig().nitriteMapper();
+ SimpleNitriteMapper documentMapper = (SimpleNitriteMapper) db.getConfig().nitriteMapper();
documentMapper.registerEntityConverter(new TestObject.Converter());
documentMapper.registerEntityConverter(new TestObject2.Converter());
diff --git a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/NitriteStressTest.java b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/NitriteStressTest.java
index f556c9c8c..5fc8cc7f4 100644
--- a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/NitriteStressTest.java
+++ b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/NitriteStressTest.java
@@ -20,13 +20,14 @@
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlSchemaType;
import lombok.Data;
+import lombok.extern.slf4j.Slf4j;
import org.dizitart.no2.Nitrite;
import org.dizitart.no2.collection.Document;
import org.dizitart.no2.collection.DocumentCursor;
import org.dizitart.no2.collection.NitriteCollection;
import org.dizitart.no2.common.mapper.EntityConverter;
import org.dizitart.no2.common.mapper.NitriteMapper;
-import org.dizitart.no2.common.mapper.SimpleDocumentMapper;
+import org.dizitart.no2.common.mapper.SimpleNitriteMapper;
import org.dizitart.no2.filters.Filter;
import org.dizitart.no2.index.IndexOptions;
import org.dizitart.no2.index.IndexType;
@@ -54,6 +55,7 @@
/**
* @author Anindya Chatterjee
*/
+@Slf4j
public class NitriteStressTest {
private static final int TEST_SET_COUNT = 15000;
private final PodamFactory podamFactory = new PodamFactoryImpl();
@@ -67,21 +69,18 @@ public class NitriteStressTest {
@Before
public void before() {
db = createDb(fileName);
- SimpleDocumentMapper documentMapper = (SimpleDocumentMapper) db.getConfig().nitriteMapper();
+ SimpleNitriteMapper documentMapper = (SimpleNitriteMapper) db.getConfig().nitriteMapper();
documentMapper.registerEntityConverter(new TestDto.Converter());
documentMapper.registerEntityConverter(new PerfTest.Converter());
documentMapper.registerEntityConverter(new PerfTestIndexed.Converter());
collection = db.getCollection("test");
- System.out.println(fileName);
}
@After
public void cleanUp() {
if (db != null && !db.isClosed()) {
- long start = System.currentTimeMillis();
db.close();
- System.out.println("Time to compact and close - " + (System.currentTimeMillis() - start) / 1000 + " seconds");
}
deleteDb(fileName);
@@ -90,7 +89,7 @@ public void cleanUp() {
@Test
public void stressTest() {
ObjectRepository testRepository = db.getRepository(TestDto.class);
- SimpleDocumentMapper documentMapper = (SimpleDocumentMapper) db.getConfig().nitriteMapper();
+ SimpleNitriteMapper documentMapper = (SimpleNitriteMapper) db.getConfig().nitriteMapper();
documentMapper.registerEntityConverter(new TestDto.Converter());
testRepository.createIndex(IndexOptions.indexOptions(IndexType.FULL_TEXT), "lastName");
testRepository.createIndex(IndexOptions.indexOptions(IndexType.NON_UNIQUE), "birthDate");
@@ -102,7 +101,7 @@ public void stressTest() {
counter++;
}
} catch (Throwable t) {
- System.err.println("Crashed after " + counter + " records");
+ log.error("Error occurred", t);
throw t;
}
@@ -120,38 +119,23 @@ public void testIssue41() {
AtomicLong counter = new AtomicLong(System.currentTimeMillis());
PodamFactory factory = new PodamFactoryImpl();
- long start = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
Document doc = Document.createDocument();
doc.put("number", random.nextDouble());
doc.put("name", factory.manufacturePojo(String.class));
doc.put("counter", counter.getAndIncrement());
collection.insert(doc);
- if (i % 10000 == 0) {
- System.out.println(i + " entries written");
- }
}
- System.out.println("Records inserted in " + ((System.currentTimeMillis() - start) / (1000 * 60)) + " minutes");
if (db.hasUnsavedChanges()) {
db.commit();
}
- start = System.currentTimeMillis();
DocumentCursor cursor = collection.find();
- System.out.println("Size ->" + cursor.size());
- System.out.println("Records size calculated in " + ((System.currentTimeMillis() - start) / (1000)) + " seconds");
- int i = 0;
- start = System.currentTimeMillis();
for (Document element : cursor) {
assertNotNull(element);
- i++;
- if (i % 10000 == 0) {
- System.out.println(i + " entries processed");
- }
}
- System.out.println("Iteration completed in " + ((System.currentTimeMillis() - start) / (1000)) + " seconds");
}
@Test
@@ -168,17 +152,11 @@ public void testRepoPerformanceWithIndex() {
// actual calculation
repo = db.getRepository(PerfTestIndexed.class);
- long start = System.currentTimeMillis();
for (PerfTestIndexed item : items) {
repo.insert(item);
}
- long diff = System.currentTimeMillis() - start;
- System.out.println("Time take to insert 10000 indexed items - " + diff + "ms");
- start = System.currentTimeMillis();
repo.remove(Filter.ALL);
- diff = System.currentTimeMillis() - start;
- System.out.println("Time take to remove 10000 indexed items - " + diff + "ms");
}
@Test
@@ -195,17 +173,11 @@ public void testRepoPerformanceWithoutIndex() {
// actual calculation
repo = db.getRepository(PerfTest.class);
- long start = System.currentTimeMillis();
for (PerfTest item : items) {
repo.insert(item);
}
- long diff = System.currentTimeMillis() - start;
- System.out.println("Time take to insert 10000 non-indexed items - " + diff + "ms");
- start = System.currentTimeMillis();
repo.remove(Filter.ALL);
- diff = System.currentTimeMillis() - start;
- System.out.println("Time take to remove 10000 non-indexed items - " + diff + "ms");
}
private List createTestSet() {
diff --git a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/NitriteTest.java b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/NitriteTest.java
index 449b7ffe0..02199d0b4 100644
--- a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/NitriteTest.java
+++ b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/NitriteTest.java
@@ -19,7 +19,7 @@
import org.dizitart.no2.Nitrite;
import org.dizitart.no2.collection.NitriteCollection;
-import org.dizitart.no2.common.mapper.SimpleDocumentMapper;
+import org.dizitart.no2.common.mapper.SimpleNitriteMapper;
import org.dizitart.no2.integration.repository.data.ClassA;
import org.dizitart.no2.integration.repository.data.ClassBConverter;
import org.junit.After;
@@ -39,7 +39,7 @@ public class NitriteTest {
@Before
public void setUp() {
db = createDb(fileName);
- SimpleDocumentMapper nitriteMapper = (SimpleDocumentMapper) db.getConfig().nitriteMapper();
+ SimpleNitriteMapper nitriteMapper = (SimpleNitriteMapper) db.getConfig().nitriteMapper();
nitriteMapper.registerEntityConverter(new ClassA.ClassAConverter());
nitriteMapper.registerEntityConverter(new ClassBConverter());
diff --git a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/Retry.java b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/Retry.java
index 3d6a27d11..039a518c0 100644
--- a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/Retry.java
+++ b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/Retry.java
@@ -17,6 +17,7 @@
package org.dizitart.no2.integration;
+import lombok.extern.slf4j.Slf4j;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
@@ -24,6 +25,7 @@
/**
* @author Anindya Chatterjee
*/
+@Slf4j
public class Retry implements TestRule {
private final int retryCount;
@@ -48,11 +50,13 @@ public void evaluate() throws Throwable {
return;
} catch (Throwable t) {
caughtThrowable = t;
- System.err.println(description.getDisplayName() + ": run " + (i + 1) + " failed");
+ log.warn(description.getDisplayName() + ": run " + (i + 1) + " failed");
}
}
- System.err.println(description.getDisplayName() + ": giving up after " + retryCount + " failures");
- throw caughtThrowable;
+ log.error(description.getDisplayName() + ": giving up after " + retryCount + " failures");
+ if (caughtThrowable != null) {
+ throw caughtThrowable;
+ }
}
};
}
diff --git a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/SerializabilityTest.java b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/SerializabilityTest.java
index 09ca50080..9f0bf35a6 100644
--- a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/SerializabilityTest.java
+++ b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/SerializabilityTest.java
@@ -18,6 +18,7 @@
package org.dizitart.no2.integration;
import lombok.Data;
+import lombok.extern.slf4j.Slf4j;
import org.dizitart.no2.Nitrite;
import org.dizitart.no2.collection.Document;
import org.dizitart.no2.collection.NitriteCollection;
@@ -33,6 +34,7 @@
/**
* @author Anindya Chatterjee
*/
+@Slf4j
public class SerializabilityTest {
private NitriteCollection collection;
private File dbFile;
@@ -69,9 +71,8 @@ public void testSerializabilityValidation() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
- e.printStackTrace();
+ log.error("Error while sleeping", e);
}
- System.out.println("Write " + i + " completed");
}
}
@@ -85,9 +86,8 @@ public void testSerializablity() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
- e.printStackTrace();
+ log.error("Error while sleeping", e);
}
- System.out.println("Write " + i + " completed");
}
}
diff --git a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/TestUtil.java b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/TestUtil.java
index 4a0034399..f2f411019 100644
--- a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/TestUtil.java
+++ b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/TestUtil.java
@@ -22,7 +22,6 @@
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
-import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.dizitart.no2.Nitrite;
import org.dizitart.no2.collection.Document;
@@ -52,9 +51,12 @@ public static String getRandomTempDbFile() {
return file.getPath() + File.separator + UUID.randomUUID() + ".db";
}
- @SneakyThrows
public static void deleteDb(String filePath) {
- Files.delete(Paths.get(filePath));
+ try {
+ Files.delete(Paths.get(filePath));
+ } catch (Exception e) {
+ log.error("Error while deleting db", e);
+ }
}
public static > boolean isSorted(Iterable iterable, boolean ascending) {
diff --git a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/collection/CollectionCompoundIndexTest.java b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/collection/CollectionCompoundIndexTest.java
index 8d37792ed..ffa990763 100644
--- a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/collection/CollectionCompoundIndexTest.java
+++ b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/collection/CollectionCompoundIndexTest.java
@@ -25,6 +25,7 @@
import org.dizitart.no2.common.WriteResult;
import org.dizitart.no2.filters.Filter;
import org.dizitart.no2.index.IndexType;
+import org.junit.Assert;
import org.junit.Test;
import java.util.Date;
@@ -151,7 +152,7 @@ public void testDeleteWithIndex() {
@Test
public void testRebuildIndexOnRunningIndex() {
insert();
- db.getStore().subscribe(System.out::println);
+ db.getStore().subscribe(Assert::assertNotNull);
collection.createIndex("firstName", "lastName");
collection.rebuildIndex("firstName", "lastName");
diff --git a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/collection/CollectionIndexTest.java b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/collection/CollectionIndexTest.java
index 4a45fa055..28a09d17d 100644
--- a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/collection/CollectionIndexTest.java
+++ b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/collection/CollectionIndexTest.java
@@ -278,7 +278,6 @@ public void testIndexEvent() {
break;
}
assertTrue(eventInfo.getItem() instanceof String);
- System.out.println(eventInfo.getEventType() + " for field " + eventInfo.getItem());
});
collection.createIndex(indexOptions(IndexType.NON_UNIQUE), "first");
diff --git a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/collection/CollectionJoinTest.java b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/collection/CollectionJoinTest.java
index caff44d61..3085b3625 100644
--- a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/collection/CollectionJoinTest.java
+++ b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/collection/CollectionJoinTest.java
@@ -100,7 +100,6 @@ public void testJoinAll() {
} else if (document.get("firstName") == "fn3") {
assertNull(document.get("personalDetails"));
}
- System.out.println(document);
}
}
}
diff --git a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/collection/CollectionUpdateTest.java b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/collection/CollectionUpdateTest.java
index 86bff59b5..4dad51555 100644
--- a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/collection/CollectionUpdateTest.java
+++ b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/collection/CollectionUpdateTest.java
@@ -214,7 +214,6 @@ public void updateAfterAttributeRemoval() {
assertEquals(savedDoc1, clonedDoc1);
clonedDoc1.put("group", null);
-// clonedDoc1.remove("group");
assertEquals(1, coll.update(clonedDoc1).getAffectedCount());
Document savedDoc2 = coll.find(Filter.ALL).firstOrNull();
@@ -222,6 +221,38 @@ public void updateAfterAttributeRemoval() {
assertNull(savedDoc2.get("group"));
}
+ @Test
+ public void updateNestedDocument() {
+ // github issue - 704
+ Document doc1 = createDocument("conversation",
+ createDocument("unread",
+ createDocument("me", 1).put("other", 2)));
+ Document doc2 = createDocument("conversation",
+ createDocument("unread",
+ createDocument("me", 10).put("other", 4)));
+
+ NitriteCollection coll = db.getCollection("test_updateNestedDocument");
+ coll.remove(Filter.ALL);
+ coll.insert(doc1, doc2);
+
+ DocumentCursor cursor = coll.find(where("conversation.unread.me").gt(5));
+ assertEquals(cursor.size(), 1);
+
+ Document update = createDocument("conversation",
+ createDocument("unread",
+ createDocument("me", 0)));
+ coll.update(Filter.ALL, update);
+
+ cursor = coll.find(where("conversation.unread.me").gt(5));
+ assertEquals(cursor.size(), 0);
+
+ cursor = coll.find(where("conversation.unread.other").lt(5));
+ assertEquals(cursor.size(), 2);
+
+ cursor = coll.find(where("conversation.unread.other").lt(5).not());
+ assertEquals(cursor.size(), 0);
+ }
+
@Test(expected = NotIdentifiableException.class)
public void testUpdateWithoutId() {
NitriteCollection collection = db.getCollection("test");
diff --git a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/collection/FieldProcessorTest.java b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/collection/FieldProcessorTest.java
deleted file mode 100644
index 08cf8fc9f..000000000
--- a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/collection/FieldProcessorTest.java
+++ /dev/null
@@ -1,202 +0,0 @@
-/*
- * Copyright (c) 2017-2021 Nitrite author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package org.dizitart.no2.integration.collection;
-
-import org.dizitart.no2.collection.Document;
-import org.dizitart.no2.collection.NitriteCollection;
-import org.dizitart.no2.collection.NitriteId;
-import org.dizitart.no2.common.WriteResult;
-import org.dizitart.no2.common.crypto.AESEncryptor;
-import org.dizitart.no2.common.crypto.Encryptor;
-import org.dizitart.no2.common.processors.Processor;
-import org.dizitart.no2.common.processors.StringFieldEncryptionProcessor;
-import org.dizitart.no2.exceptions.NitriteSecurityException;
-import org.dizitart.no2.store.NitriteMap;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.nio.charset.StandardCharsets;
-import java.util.Date;
-import java.util.List;
-
-import static org.dizitart.no2.common.util.Iterables.toList;
-import static org.dizitart.no2.filters.FluentFilter.where;
-import static org.junit.Assert.*;
-
-/**
- * @author Anindya Chatterjee
- */
-public class FieldProcessorTest extends BaseCollectionTest {
-
- private Encryptor encryptor;
- private NitriteCollection collection;
- private Processor cvvProcessor;
-
- @Before
- public void setUp() {
- super.setUp();
-
- encryptor = new AESEncryptor("s3k4e8");
- cvvProcessor = new Processor() {
- @Override
- public Document processBeforeWrite(Document document) {
- String cvv = document.get("cvv", String.class);
- String encryptedCvv = encryptor.encrypt(cvv.getBytes(StandardCharsets.UTF_8));
- document.put("cvv", encryptedCvv);
- return document;
- }
-
- @Override
- public Document processAfterRead(Document document) {
- String encryptedCvv = document.get("cvv", String.class);
- String cvv = encryptor.decrypt(encryptedCvv);
- document.put("cvv", cvv);
- return document;
- }
- };
- StringFieldEncryptionProcessor creditCardProcessor = new StringFieldEncryptionProcessor(encryptor);
- creditCardProcessor.addFields("creditCardNumber");
-
- collection = db.getCollection("encryption-test");
- collection.addProcessor(creditCardProcessor);
-
- Document document = Document.createDocument("name", "John Doe")
- .put("creditCardNumber", "5548960345687452")
- .put("cvv", "007")
- .put("expiryDate", new Date());
- collection.insert(document);
-
- document = Document.createDocument("name", "Jane Doe")
- .put("creditCardNumber", "5500960345687452")
- .put("cvv", "008")
- .put("expiryDate", new Date());
- collection.insert(document);
-
- cvvProcessor.process(collection);
- collection.addProcessor(cvvProcessor);
- }
-
- @Test
- public void testFieldEncryptionInNitriteMap() {
- NitriteMap nitriteMap = collection.getStore().openMap("encryption-test",
- NitriteId.class, Document.class);
-
- List documents = toList(nitriteMap.values());
- for (Document document : documents) {
- if (document.get("creditCardNumber", String.class).equalsIgnoreCase("5548960345687452")) {
- Assert.fail("unencrypted secret text found");
- }
-
- if (document.get("creditCardNumber", String.class).equalsIgnoreCase("5500960345687452")) {
- Assert.fail("unencrypted secret text found");
- }
-
- if (document.get("cvv", String.class).equalsIgnoreCase("008")) {
- Assert.fail("unencrypted secret text found");
- }
-
- if (document.get("cvv", String.class).equalsIgnoreCase("007")) {
- Assert.fail("unencrypted secret text found");
- }
- }
- }
-
- @Test
- public void testSuccessfulDecryption() {
- Document document = collection.find(where("name").eq("Jane Doe")).firstOrNull();
- assertNotNull(document);
-
- assertEquals(document.get("creditCardNumber", String.class), "5500960345687452");
- assertEquals(document.get("cvv", String.class), "008");
-
- document = collection.find(where("name").eq("John Doe")).firstOrNull();
- assertNotNull(document);
-
- assertEquals(document.get("creditCardNumber", String.class), "5548960345687452");
- assertEquals(document.get("cvv", String.class), "007");
- }
-
- @Test(expected = NitriteSecurityException.class)
- public void testFailedDecryption() {
- Encryptor wrongEncryptor = new AESEncryptor("secret");
-
- collection = db.getCollection("encryption-test");
- collection.addProcessor(new Processor() {
- @Override
- public Document processBeforeWrite(Document document) {
- String creditCardNumber = document.get("creditCardNumber", String.class);
- String encryptedCreditCardNumber = encryptor.encrypt(creditCardNumber.getBytes(StandardCharsets.UTF_8));
- document.put("creditCardNumber", encryptedCreditCardNumber);
- return document;
- }
-
- @Override
- public Document processAfterRead(Document document) {
- String encryptedCreditCardNumber = document.get("creditCardNumber", String.class);
- String creditCardNumber = wrongEncryptor.decrypt(encryptedCreditCardNumber);
- document.put("creditCardNumber", creditCardNumber);
- return document;
- }
- });
-
- Document document = Document.createDocument("name", "John Doe")
- .put("creditCardNumber", "5548960345687452")
- .put("cvv", "007")
- .put("expiryDate", new Date());
- collection.insert(document);
-
- document = Document.createDocument("name", "Jane Doe")
- .put("creditCardNumber", "5500960345687452")
- .put("cvv", "008")
- .put("expiryDate", new Date());
- collection.insert(document);
-
- collection.find(where("name").eq("Jane Doe")).firstOrNull();
- }
-
- @Test
- public void testSearchOnEncryptedField() {
- Document document = collection.find(where("cvv").eq("008")).firstOrNull();
- assertNull(document);
- }
-
- @Test
- public void testUpdateEncryptedField() {
- Document document = Document.createDocument("name", "John Doe")
- .put("creditCardNumber", "00000000000000")
- .put("cvv", "007")
- .put("expiryDate", new Date());
-
- WriteResult writeResult = collection.update(where("name").eq("John Doe"), document);
- assertEquals(writeResult.getAffectedCount(), 1);
-
- document = collection.find(where("name").eq("John Doe")).firstOrNull();
- assertNotNull(document);
-
- assertEquals(document.get("creditCardNumber", String.class), "00000000000000");
- assertEquals(document.get("cvv", String.class), "007");
- }
-
- @Test
- public void testIndexOnEncryptedField() {
- collection.createIndex("cvv");
- Document document = collection.find(where("cvv").eq("008")).firstOrNull();
- assertNull(document);
- }
-}
diff --git a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/event/EventTest.java b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/event/EventTest.java
index d9b4e5816..7bb8e8f47 100644
--- a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/event/EventTest.java
+++ b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/event/EventTest.java
@@ -18,7 +18,7 @@
package org.dizitart.no2.integration.event;
import org.dizitart.no2.collection.UpdateOptions;
-import org.dizitart.no2.common.mapper.SimpleDocumentMapper;
+import org.dizitart.no2.common.mapper.SimpleNitriteMapper;
import org.dizitart.no2.integration.Retry;
import org.dizitart.no2.integration.repository.data.Employee;
import org.dizitart.no2.Nitrite;
@@ -120,7 +120,7 @@ public void setUp() {
db = nitriteBuilder.openOrCreate();
}
- SimpleDocumentMapper documentMapper = (SimpleDocumentMapper) db.getConfig().nitriteMapper();
+ SimpleNitriteMapper documentMapper = (SimpleNitriteMapper) db.getConfig().nitriteMapper();
documentMapper.registerEntityConverter(new Employee.EmployeeConverter());
employeeRepository = db.getRepository(Employee.class);
@@ -182,7 +182,6 @@ public void testDelete() {
employeeRepository.remove(where("empId").eq(1L));
await().atMost(1, TimeUnit.SECONDS).until(listenerPrepared(EventType.Remove));
- System.out.println("Action - " + listener.getAction());
assertEquals(listener.getAction(), EventType.Remove);
assertNotNull(listener.getItem());
}
diff --git a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/migration/MigrationTest.java b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/migration/MigrationTest.java
index 2843ba4c5..887e95d01 100644
--- a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/migration/MigrationTest.java
+++ b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/migration/MigrationTest.java
@@ -18,7 +18,7 @@
package org.dizitart.no2.integration.migration;
import com.github.javafaker.Faker;
-import org.dizitart.no2.common.mapper.SimpleDocumentMapper;
+import org.dizitart.no2.common.mapper.SimpleNitriteMapper;
import org.dizitart.no2.integration.Retry;
import org.dizitart.no2.Nitrite;
import org.dizitart.no2.collection.Document;
@@ -58,7 +58,7 @@ public class MigrationTest {
@Before
public void setUp() {
db = createDb(dbPath);
- SimpleDocumentMapper documentMapper = (SimpleDocumentMapper) db.getConfig().nitriteMapper();
+ SimpleNitriteMapper documentMapper = (SimpleNitriteMapper) db.getConfig().nitriteMapper();
documentMapper.registerEntityConverter(new OldClass.Converter());
documentMapper.registerEntityConverter(new OldClass.Literature.Converter());
documentMapper.registerEntityConverter(new NewClass.Converter());
@@ -128,7 +128,7 @@ public void migrate(InstructionSet instruction) {
.addMigrations(migration)
.openOrCreate("test-user", "test-password");
- SimpleDocumentMapper documentMapper = (SimpleDocumentMapper) db.getConfig().nitriteMapper();
+ SimpleNitriteMapper documentMapper = (SimpleNitriteMapper) db.getConfig().nitriteMapper();
documentMapper.registerEntityConverter(new OldClass.Converter());
documentMapper.registerEntityConverter(new OldClass.Literature.Converter());
documentMapper.registerEntityConverter(new NewClass.Converter());
diff --git a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/BaseObjectRepositoryTest.java b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/BaseObjectRepositoryTest.java
index f279620f0..1e08cac3e 100644
--- a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/BaseObjectRepositoryTest.java
+++ b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/BaseObjectRepositoryTest.java
@@ -19,7 +19,7 @@
import org.dizitart.no2.Nitrite;
import org.dizitart.no2.NitriteBuilder;
-import org.dizitart.no2.common.mapper.SimpleDocumentMapper;
+import org.dizitart.no2.common.mapper.SimpleNitriteMapper;
import org.dizitart.no2.integration.Retry;
import org.dizitart.no2.integration.repository.data.*;
import org.dizitart.no2.integration.repository.decorator.ManufacturerConverter;
@@ -142,7 +142,7 @@ protected void openDb() {
db = nitriteBuilder.openOrCreate();
}
- SimpleDocumentMapper documentMapper = (SimpleDocumentMapper) db.getConfig().nitriteMapper();
+ SimpleNitriteMapper documentMapper = (SimpleNitriteMapper) db.getConfig().nitriteMapper();
documentMapper.registerEntityConverter(new RepositoryJoinTest.Person.Converter());
documentMapper.registerEntityConverter(new RepositoryJoinTest.Address.Converter());
documentMapper.registerEntityConverter(new RepositoryJoinTest.PersonDetails.Converter());
diff --git a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/CustomFieldSeparatorTest.java b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/CustomFieldSeparatorTest.java
index affd45598..72886734b 100644
--- a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/CustomFieldSeparatorTest.java
+++ b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/CustomFieldSeparatorTest.java
@@ -22,7 +22,7 @@
import lombok.Setter;
import lombok.ToString;
import org.dizitart.no2.common.mapper.EntityConverter;
-import org.dizitart.no2.common.mapper.SimpleDocumentMapper;
+import org.dizitart.no2.common.mapper.SimpleNitriteMapper;
import org.dizitart.no2.integration.Retry;
import org.dizitart.no2.integration.repository.data.Company;
import org.dizitart.no2.integration.repository.data.Note;
@@ -72,7 +72,7 @@ public void setUp() {
.fieldSeparator(":")
.openOrCreate();
- SimpleDocumentMapper mapper = (SimpleDocumentMapper) db.getConfig().nitriteMapper();
+ SimpleNitriteMapper mapper = (SimpleNitriteMapper) db.getConfig().nitriteMapper();
mapper.registerEntityConverter(new Company.CompanyConverter());
mapper.registerEntityConverter(new EmployeeForCustomSeparator.EmployeeForCustomSeparatorConverter());
mapper.registerEntityConverter(new Note.NoteConverter());
diff --git a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/FieldProcessorTest.java b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/FieldProcessorTest.java
deleted file mode 100644
index 8f31d6408..000000000
--- a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/FieldProcessorTest.java
+++ /dev/null
@@ -1,194 +0,0 @@
-/*
- * Copyright (c) 2017-2021 Nitrite author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package org.dizitart.no2.integration.repository;
-
-import org.dizitart.no2.integration.repository.data.EncryptedPerson;
-import org.dizitart.no2.collection.Document;
-import org.dizitart.no2.collection.NitriteId;
-import org.dizitart.no2.common.WriteResult;
-import org.dizitart.no2.common.crypto.AESEncryptor;
-import org.dizitart.no2.common.crypto.Encryptor;
-import org.dizitart.no2.common.processors.Processor;
-import org.dizitart.no2.common.processors.StringFieldEncryptionProcessor;
-import org.dizitart.no2.exceptions.NitriteSecurityException;
-import org.dizitart.no2.repository.ObjectRepository;
-import org.dizitart.no2.store.NitriteMap;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.nio.charset.StandardCharsets;
-import java.util.Date;
-import java.util.List;
-
-import static org.dizitart.no2.common.util.Iterables.toList;
-import static org.dizitart.no2.common.util.ObjectUtils.findRepositoryName;
-import static org.dizitart.no2.filters.FluentFilter.where;
-import static org.junit.Assert.*;
-
-/**
- * @author Anindya Chatterjee
- */
-public class FieldProcessorTest extends BaseObjectRepositoryTest {
- private ObjectRepository persons;
- private StringFieldEncryptionProcessor fieldProcessor;
-
- @Before
- public void setUp() {
- super.setUp();
- persons = db.getRepository(EncryptedPerson.class);
- fieldProcessor = new StringFieldEncryptionProcessor("s3k4e8");
- fieldProcessor.addFields("creditCardNumber", "cvv");
-
- EncryptedPerson person = new EncryptedPerson();
- person.setName("John Doe");
- person.setCreditCardNumber("5548960345687452");
- person.setCvv("007");
- person.setExpiryDate(new Date());
-
- persons.insert(person);
-
- // process existing data
- fieldProcessor.process(persons);
-
- // add for further changes
- persons.addProcessor(fieldProcessor);
-
- person = new EncryptedPerson();
- person.setName("Jane Doe");
- person.setCreditCardNumber("5500960345687452");
- person.setCvv("008");
- person.setExpiryDate(new Date());
- persons.insert(person);
- }
-
- @Test
- public void testFieldEncryptionInNitriteMap() {
- NitriteMap nitriteMap = persons.getDocumentCollection().getStore()
- .openMap(findRepositoryName(EncryptedPerson.class, null), NitriteId.class, Document.class);
-
- List documents = toList(nitriteMap.values());
- for (Document document : documents) {
- if (document.get("creditCardNumber", String.class).equalsIgnoreCase("5548960345687452")) {
- Assert.fail("unencrypted secret text found");
- }
-
- if (document.get("creditCardNumber", String.class).equalsIgnoreCase("5500960345687452")) {
- Assert.fail("unencrypted secret text found");
- }
-
- if (document.get("cvv", String.class).equalsIgnoreCase("008")) {
- Assert.fail("unencrypted secret text found");
- }
-
- if (document.get("cvv", String.class).equalsIgnoreCase("007")) {
- Assert.fail("unencrypted secret text found");
- }
- }
- }
-
- @Test
- public void testSuccessfulDecryption() {
- EncryptedPerson person = persons.find(where("name").eq("Jane Doe")).firstOrNull();
- assertNotNull(person);
-
- assertEquals(person.getCreditCardNumber(), "5500960345687452");
- assertEquals(person.getCvv(), "008");
-
- person = persons.find(where("name").eq("John Doe")).firstOrNull();
- assertNotNull(person);
-
- assertEquals(person.getCreditCardNumber(), "5548960345687452");
- assertEquals(person.getCvv(), "007");
- }
-
- @Test(expected = NitriteSecurityException.class)
- public void testFailedDecryption() {
- ObjectRepository testPersons = db.getRepository(EncryptedPerson.class, "test");
-
- Encryptor encryptor = new AESEncryptor("secret");
- Encryptor wrongEncryptor = new AESEncryptor("secret", "AES/GCM/NoPadding",
- 5, 5, 5);
-
- testPersons.addProcessor(new Processor() {
- @Override
- public Document processBeforeWrite(Document document) {
- String creditCardNumber = document.get("creditCardNumber", String.class);
- String encryptedCreditCardNumber = encryptor.encrypt(creditCardNumber.getBytes(StandardCharsets.UTF_8));
- document.put("creditCardNumber", encryptedCreditCardNumber);
- return document;
- }
-
- @Override
- public Document processAfterRead(Document document) {
- String encryptedCreditCardNumber = document.get("creditCardNumber", String.class);
- String creditCardNumber = wrongEncryptor.decrypt(encryptedCreditCardNumber);
- document.put("creditCardNumber", creditCardNumber);
- return document;
- }
- });
-
- EncryptedPerson person = new EncryptedPerson();
- person.setName("John Doe");
- person.setCreditCardNumber("5548960345687452");
- person.setCvv("007");
- person.setExpiryDate(new Date());
-
- testPersons.insert(person);
-
- person = new EncryptedPerson();
- person.setName("Jane Doe");
- person.setCreditCardNumber("5500960345687452");
- person.setCvv("008");
- person.setExpiryDate(new Date());
- testPersons.insert(person);
-
- testPersons.find(where("name").eq("Jane Doe")).firstOrNull();
- }
-
- @Test
- public void testSearchOnEncryptedField() {
- EncryptedPerson person = persons.find(where("cvv").eq("008")).firstOrNull();
- assertNull(person);
- }
-
- @Test
- public void testUpdateEncryptedField() {
- EncryptedPerson person = new EncryptedPerson();
- person.setName("John Doe");
- person.setCreditCardNumber("00000000000000");
- person.setCvv("007");
- person.setExpiryDate(new Date());
-
- WriteResult writeResult = persons.update(where("name").eq("John Doe"), person);
- assertEquals(writeResult.getAffectedCount(), 1);
-
- person = persons.find(where("name").eq("John Doe")).firstOrNull();
- assertNotNull(person);
-
- assertEquals(person.getCreditCardNumber(), "00000000000000");
- assertEquals(person.getCvv(), "007");
- }
-
- @Test
- public void testIndexOnEncryptedField() {
- persons.createIndex("cvv");
- EncryptedPerson person = persons.find(where("cvv").eq("008")).firstOrNull();
- assertNull(person);
- }
-}
diff --git a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/NitriteIdAsIdTest.java b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/NitriteIdAsIdTest.java
index 4b776ea17..a2f83265e 100644
--- a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/NitriteIdAsIdTest.java
+++ b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/NitriteIdAsIdTest.java
@@ -17,7 +17,7 @@
package org.dizitart.no2.integration.repository;
-import org.dizitart.no2.common.mapper.SimpleDocumentMapper;
+import org.dizitart.no2.common.mapper.SimpleNitriteMapper;
import org.dizitart.no2.integration.Retry;
import org.dizitart.no2.integration.repository.data.WithNitriteId;
import org.dizitart.no2.Nitrite;
@@ -54,7 +54,7 @@ public class NitriteIdAsIdTest {
@Before
public void before() {
db = TestUtil.createDb(fileName);
- SimpleDocumentMapper documentMapper = (SimpleDocumentMapper) db.getConfig().nitriteMapper();
+ SimpleNitriteMapper documentMapper = (SimpleNitriteMapper) db.getConfig().nitriteMapper();
documentMapper.registerEntityConverter(new WithNitriteId.WithNitriteIdConverter());
repo = db.getRepository(WithNitriteId.class);
@@ -78,7 +78,6 @@ public void testNitriteIdField() {
Cursor cursor = repo.find();
for (WithNitriteId withNitriteId : cursor) {
- System.out.println(withNitriteId.name);
assertNotNull(withNitriteId.idField);
}
diff --git a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/ObjectRepositoryNegativeTest.java b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/ObjectRepositoryNegativeTest.java
index 66a816959..4f16c129e 100644
--- a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/ObjectRepositoryNegativeTest.java
+++ b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/ObjectRepositoryNegativeTest.java
@@ -17,7 +17,7 @@
package org.dizitart.no2.integration.repository;
-import org.dizitart.no2.common.mapper.SimpleDocumentMapper;
+import org.dizitart.no2.common.mapper.SimpleNitriteMapper;
import org.dizitart.no2.integration.Retry;
import org.dizitart.no2.integration.repository.data.*;
import org.dizitart.no2.Nitrite;
@@ -51,7 +51,7 @@ public class ObjectRepositoryNegativeTest {
@Before
public void setUp() {
db = TestUtil.createDb(dbPath);
- SimpleDocumentMapper documentMapper = (SimpleDocumentMapper) db.getConfig().nitriteMapper();
+ SimpleNitriteMapper documentMapper = (SimpleNitriteMapper) db.getConfig().nitriteMapper();
documentMapper.registerEntityConverter(new WithPublicField.Converter());
documentMapper.registerEntityConverter(new WithObjectId.Converter());
documentMapper.registerEntityConverter(new WithOutId.Converter());
diff --git a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/ObjectRepositoryTest.java b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/ObjectRepositoryTest.java
index d66ef2d9c..314d46188 100644
--- a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/ObjectRepositoryTest.java
+++ b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/ObjectRepositoryTest.java
@@ -24,7 +24,7 @@
import org.dizitart.no2.collection.NitriteCollection;
import org.dizitart.no2.common.mapper.EntityConverter;
import org.dizitart.no2.common.mapper.NitriteMapper;
-import org.dizitart.no2.common.mapper.SimpleDocumentMapper;
+import org.dizitart.no2.common.mapper.SimpleNitriteMapper;
import org.dizitart.no2.common.meta.Attributes;
import org.dizitart.no2.exceptions.ValidationException;
import org.dizitart.no2.index.IndexType;
@@ -70,7 +70,7 @@ public class ObjectRepositoryTest {
@Before
public void setUp() {
- SimpleDocumentMapper mapper = new SimpleDocumentMapper();
+ SimpleNitriteMapper mapper = new SimpleNitriteMapper();
mapper.registerEntityConverter(new InternalClass.Converter());
mapper.registerEntityConverter(new EmployeeEntity.Converter());
mapper.registerEntityConverter(new StressRecord.Converter());
diff --git a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/RepositorySearchTest.java b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/RepositorySearchTest.java
index 17c54b1e8..7257352d5 100644
--- a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/RepositorySearchTest.java
+++ b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/RepositorySearchTest.java
@@ -20,7 +20,7 @@
import lombok.Getter;
import org.dizitart.no2.common.WriteResult;
import org.dizitart.no2.common.mapper.EntityConverter;
-import org.dizitart.no2.common.mapper.SimpleDocumentMapper;
+import org.dizitart.no2.common.mapper.SimpleNitriteMapper;
import org.dizitart.no2.integration.repository.data.*;
import org.dizitart.no2.collection.Document;
import org.dizitart.no2.common.SortOrder;
@@ -65,8 +65,8 @@ public void testEmployeeProjection() {
assertNotNull(employeeList);
assertNotNull(subEmployeeList);
- assertTrue(employeeList.size() > 0);
- assertTrue(subEmployeeList.size() > 0);
+ assertFalse(employeeList.isEmpty());
+ assertFalse(subEmployeeList.isEmpty());
assertEquals(employeeList.size(), subEmployeeList.size());
@@ -592,7 +592,7 @@ public TestData fromDocument(Document document, NitriteMapper nitriteMapper) {
}
}
- SimpleDocumentMapper documentMapper = (SimpleDocumentMapper) db.getConfig().nitriteMapper();
+ SimpleNitriteMapper documentMapper = (SimpleNitriteMapper) db.getConfig().nitriteMapper();
documentMapper.registerEntityConverter(new Converter());
TestData data1 = new TestData(new GregorianCalendar(2020, Calendar.JANUARY, 11).getTime());
diff --git a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/UnAnnotatedObjectTest.java b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/UnAnnotatedObjectTest.java
index cf793fb10..defd452ac 100644
--- a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/UnAnnotatedObjectTest.java
+++ b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/UnAnnotatedObjectTest.java
@@ -26,8 +26,7 @@
import static org.dizitart.no2.collection.FindOptions.orderBy;
import static org.dizitart.no2.filters.FluentFilter.where;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.*;
/**
* @author Anindya Chatterjee.
@@ -45,33 +44,25 @@ public void testFind() {
cursor = aObjectRepository.find(where("b.number").eq(160).not(),
orderBy("b.number", SortOrder.Ascending).skip(0).limit(10));
- System.out.println("Available - " + !cursor.isEmpty());
- System.out.println("Total Size - " + cursor.size());
-
Iterable findRecord = cursor.project(ClassA.class);
for (ClassA classA : findRecord) {
- System.out.println(classA);
+ assertNotNull(classA);
}
cursor = aObjectRepository.find(where("b.number").eq(160).not(),
orderBy("b.number", SortOrder.Descending).skip(2).limit(7));
- System.out.println("Available - " + !cursor.isEmpty());
- System.out.println("Total Size - " + cursor.size());
-
findRecord = cursor.project(ClassA.class);
for (ClassA classA : findRecord) {
- System.out.println(classA);
+ assertNotNull(classA);
}
cursor = cObjectRepository.find(where("id").gt(900),
orderBy("id", SortOrder.Descending).skip(2).limit(7));
- System.out.println("Available - " + !cursor.isEmpty());
- System.out.println("Total Size - " + cursor.size());
Iterable findRecordC = cursor.project(ClassC.class);
for (ClassC classC : findRecordC) {
- System.out.println(classC);
+ assertNotNull(classC);
}
}
}
diff --git a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/UniversalTextTokenizerTest.java b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/UniversalTextTokenizerTest.java
index 59d6681ba..b49ebde04 100644
--- a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/UniversalTextTokenizerTest.java
+++ b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/repository/UniversalTextTokenizerTest.java
@@ -22,7 +22,7 @@
import org.dizitart.no2.collection.Document;
import org.dizitart.no2.common.mapper.EntityConverter;
import org.dizitart.no2.common.mapper.NitriteMapper;
-import org.dizitart.no2.common.mapper.SimpleDocumentMapper;
+import org.dizitart.no2.common.mapper.SimpleNitriteMapper;
import org.dizitart.no2.index.IndexType;
import org.dizitart.no2.index.NitriteTextIndexer;
import org.dizitart.no2.index.fulltext.Languages;
@@ -56,7 +56,7 @@ public class UniversalTextTokenizerTest extends BaseObjectRepositoryTest {
@Override
public void setUp() {
openDb();
- SimpleDocumentMapper documentMapper = (SimpleDocumentMapper) db.getConfig().nitriteMapper();
+ SimpleNitriteMapper documentMapper = (SimpleNitriteMapper) db.getConfig().nitriteMapper();
documentMapper.registerEntityConverter(new TextData.Converter());
textRepository = db.getRepository(TextData.class);
@@ -142,7 +142,6 @@ public void testUniversalFullTextIndexing() {
Cursor cursor = textRepository.find(where("text").text("Lorem"));
assertEquals(cursor.size(), 2);
for (TextData data : cursor) {
- System.out.println("Id for English text -> " + data.id);
if (data.id % 2 == 0 || data.id % 3 == 0 || data.id % 5 == 0) {
fail();
}
@@ -151,7 +150,6 @@ public void testUniversalFullTextIndexing() {
cursor = textRepository.find(where("text").text("শহর"));
assertEquals(cursor.size(), 5);
for (TextData data : cursor) {
- System.out.println("Id for Bengali text -> " + data.id);
if (data.id % 2 != 0) {
fail();
}
@@ -162,7 +160,6 @@ public void testUniversalFullTextIndexing() {
cursor = textRepository.find(where("text").text("*転閉*"));
assertEquals(cursor.size(), 2);
for (TextData data : cursor) {
- System.out.println("Id for Chinese text -> " + data.id);
if (data.id % 3 != 0) {
fail();
}
@@ -172,7 +169,6 @@ public void testUniversalFullTextIndexing() {
if (isCompressed) {
assertEquals(cursor.size(), 1);
for (TextData data : cursor) {
- System.out.println("Id for Arabic text -> " + data.id);
if (data.id % 5 != 0) {
fail();
}
diff --git a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/transaction/TransactionCollectionTest.java b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/transaction/TransactionCollectionTest.java
index 6e3052aaa..b21bcf420 100644
--- a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/transaction/TransactionCollectionTest.java
+++ b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/transaction/TransactionCollectionTest.java
@@ -18,18 +18,21 @@
package org.dizitart.no2.integration.transaction;
import com.github.javafaker.Faker;
-import org.dizitart.no2.integration.collection.BaseCollectionTest;
+import lombok.extern.slf4j.Slf4j;
import org.dizitart.no2.collection.Document;
import org.dizitart.no2.collection.NitriteCollection;
import org.dizitart.no2.common.meta.Attributes;
-import org.dizitart.no2.exceptions.NitriteIOException;
import org.dizitart.no2.exceptions.TransactionException;
import org.dizitart.no2.index.IndexType;
+import org.dizitart.no2.integration.collection.BaseCollectionTest;
import org.dizitart.no2.transaction.Session;
import org.dizitart.no2.transaction.Transaction;
import org.junit.Test;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -44,6 +47,7 @@
/**
* @author Anindya Chatterjee
*/
+@Slf4j
public class TransactionCollectionTest extends BaseCollectionTest {
@Test
@@ -544,7 +548,7 @@ public void testConcurrentInsertAndRemove() {
transaction.commit();
} catch (Exception e) {
- e.printStackTrace();
+ log.error("Error in transaction", e);
transaction.rollback();
} finally {
transaction.close();
@@ -558,7 +562,7 @@ public void testConcurrentInsertAndRemove() {
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
- e.printStackTrace();
+ log.error("Error in transaction", e);
}
});
@@ -588,7 +592,7 @@ public void testConcurrentInsert() {
transaction.commit();
} catch (Exception e) {
- e.printStackTrace();
+ log.error("Error in transaction", e);
transaction.rollback();
} finally {
transaction.close();
@@ -602,7 +606,7 @@ public void testConcurrentInsert() {
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
- e.printStackTrace();
+ log.error("Error in transaction", e);
}
});
@@ -637,7 +641,7 @@ public void testConcurrentUpdate() {
transaction.commit();
} catch (Exception e) {
- e.printStackTrace();
+ log.error("Error in transaction", e);
transaction.rollback();
} finally {
transaction.close();
@@ -651,7 +655,7 @@ public void testConcurrentUpdate() {
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
- e.printStackTrace();
+ log.error("Error in transaction", e);
}
});
diff --git a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/transaction/TransactionRepositoryTest.java b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/transaction/TransactionRepositoryTest.java
index 4adab1075..e699c1b5e 100644
--- a/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/transaction/TransactionRepositoryTest.java
+++ b/nitrite-mvstore-adapter/src/test/java/org/dizitart/no2/integration/transaction/TransactionRepositoryTest.java
@@ -18,6 +18,7 @@
package org.dizitart.no2.integration.transaction;
import com.github.javafaker.Faker;
+import lombok.extern.slf4j.Slf4j;
import org.dizitart.no2.collection.Document;
import org.dizitart.no2.collection.NitriteCollection;
import org.dizitart.no2.common.meta.Attributes;
@@ -45,6 +46,7 @@
/**
* @author Anindya Chatterjee
*/
+@Slf4j
public class TransactionRepositoryTest extends BaseObjectRepositoryTest {
@Test
@@ -588,7 +590,7 @@ public void testConcurrentInsertAndRemove() {
transaction.commit();
} catch (Exception e) {
- e.printStackTrace();
+ log.error("Error in concurrent insert/remove", e);
transaction.rollback();
} finally {
transaction.close();
@@ -602,7 +604,7 @@ public void testConcurrentInsertAndRemove() {
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
- e.printStackTrace();
+ log.error("Error in concurrent insert/remove", e);
}
});
@@ -632,7 +634,7 @@ public void testConcurrentInsert() {
transaction.commit();
} catch (Exception e) {
- e.printStackTrace();
+ log.error("Error in concurrent insert", e);
transaction.rollback();
} finally {
transaction.close();
@@ -646,7 +648,7 @@ public void testConcurrentInsert() {
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
- e.printStackTrace();
+ log.error("Error in concurrent insert", e);
}
});
@@ -679,7 +681,7 @@ public void testConcurrentUpdate() {
transaction.commit();
} catch (Exception e) {
- e.printStackTrace();
+ log.error("Error in concurrent update", e);
transaction.rollback();
} finally {
transaction.close();
@@ -693,7 +695,7 @@ public void testConcurrentUpdate() {
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
- e.printStackTrace();
+ log.error("Error in concurrent update", e);
}
});
diff --git a/nitrite-rocksdb-adapter/pom.xml b/nitrite-rocksdb-adapter/pom.xml
index 68187b12f..accead5d0 100644
--- a/nitrite-rocksdb-adapter/pom.xml
+++ b/nitrite-rocksdb-adapter/pom.xml
@@ -149,6 +149,19 @@
org.apache.maven.plugins
maven-javadoc-plugin
+
+
+ **/*Serializer.java
+ **/*Serializers.java
+ **/*KryoObjectFormatter.java
+ **/*CleaningAction.java
+ **/*Constants.java
+ **/*RocksDBMap.java
+ **/*RocksDBReference.java
+ **/*RocksDBRTree.java
+ **/*RocksDBStore.java
+
+
org.apache.maven.plugins
diff --git a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/CleaningAction.java b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/CleaningAction.java
index acc30479a..128dc241b 100644
--- a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/CleaningAction.java
+++ b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/CleaningAction.java
@@ -1,5 +1,9 @@
package org.dizitart.no2.rocksdb;
+/**
+ * @since 4.0
+ * @author Anindya Chatterjee
+ */
class CleaningAction implements Runnable {
private final AutoCloseable resource;
diff --git a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/Constants.java b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/Constants.java
index acd13e6c6..d3a495b0f 100644
--- a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/Constants.java
+++ b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/Constants.java
@@ -19,6 +19,7 @@
import java.lang.ref.Cleaner;
/**
+ * @since 4.0
* @author Anindya Chatterjee
*/
public class Constants {
diff --git a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/EntrySet.java b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/EntrySet.java
index 4b22bb002..b00e7898b 100644
--- a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/EntrySet.java
+++ b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/EntrySet.java
@@ -6,6 +6,10 @@
import java.util.Iterator;
+/**
+ * @since 4.0
+ * @author Anindya Chatterjee
+ */
class EntrySet implements Iterable> {
private final ObjectFormatter objectFormatter;
private final RocksDB rocksDB;
diff --git a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/KeySet.java b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/KeySet.java
index a39ff3621..9c891e6ff 100644
--- a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/KeySet.java
+++ b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/KeySet.java
@@ -10,6 +10,10 @@
import static org.dizitart.no2.rocksdb.Constants.CLEANER;
+/**
+ * @since 4.0
+ * @author Anindya Chatterjee
+ */
class KeySet implements Iterable {
private final ObjectFormatter objectFormatter;
private final RocksDB rocksDB;
diff --git a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/RocksDBConfig.java b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/RocksDBConfig.java
index 6c2652170..94a830835 100644
--- a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/RocksDBConfig.java
+++ b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/RocksDBConfig.java
@@ -15,24 +15,58 @@
import java.util.HashSet;
import java.util.Set;
+/**
+ * Configuration class for RocksDB store. It implements the {@link StoreConfig}
+ * interface.
+ *
+ * @since 4.0
+ * @see StoreConfig
+ * @see RocksDBModule
+ * @see RocksDBModuleBuilder
+ * @author Anindya Chatterjee
+ */
@Accessors(fluent = true)
public class RocksDBConfig implements StoreConfig {
- @Getter @Setter(AccessLevel.PACKAGE)
+ @Getter
+ @Setter(AccessLevel.PACKAGE)
+ /**
+ * The set of event listeners registered with this configuration.
+ */
private Set eventListeners;
- @Getter @Setter(AccessLevel.PACKAGE)
+ @Getter
+ @Setter(AccessLevel.PACKAGE)
+ /**
+ * The RocksDB {@link Options} used to configure the database instance.
+ */
private Options options;
- @Getter @Setter(AccessLevel.PACKAGE)
+ @Getter
+ @Setter(AccessLevel.PACKAGE)
+ /**
+ * The RocksDB {@link DBOptions} used to configure the database instance.
+ */
private DBOptions dbOptions;
- @Getter @Setter(AccessLevel.PACKAGE)
+ @Getter
+ @Setter(AccessLevel.PACKAGE)
+ /**
+ * The RocksDB {@link ColumnFamilyOptions} used to configure the database instance.
+ */
private ColumnFamilyOptions columnFamilyOptions;
- @Getter @Setter(AccessLevel.PACKAGE)
+ @Getter
+ @Setter(AccessLevel.PACKAGE)
+ /**
+ * The file path of the RocksDB data store.
+ */
private String filePath;
- @Getter @Setter(AccessLevel.PACKAGE)
+ @Getter
+ @Setter(AccessLevel.PACKAGE)
+ /**
+ * The object formatter used to serialize and deserialize objects.
+ */
private ObjectFormatter objectFormatter;
RocksDBConfig() {
@@ -40,11 +74,21 @@ public class RocksDBConfig implements StoreConfig {
objectFormatter = new KryoObjectFormatter();
}
+ /**
+ * Adds a store event listener to the configuration.
+ *
+ * @param listener the store event listener to add
+ */
@Override
public void addStoreEventListener(StoreEventListener listener) {
eventListeners.add(listener);
}
+ /**
+ * Returns whether the RocksDB instance is in memory or not.
+ *
+ * @return {@code true} if the RocksDB instance is in memory; {@code false} otherwise.
+ */
@Override
public final boolean isInMemory() {
return false;
diff --git a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/RocksDBMap.java b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/RocksDBMap.java
index 6beb12ba0..55ebf109f 100644
--- a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/RocksDBMap.java
+++ b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/RocksDBMap.java
@@ -20,7 +20,11 @@
import static org.dizitart.no2.common.util.ValidationUtils.notNull;
-@Slf4j
+/**
+ * @since 4.0
+ * @author Anindya Chatterjee
+ */
+@Slf4j(topic = "nitrite-rocksdb")
public class RocksDBMap implements NitriteMap {
private final String mapName;
private final RocksDBReference reference;
diff --git a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/RocksDBModule.java b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/RocksDBModule.java
index acca1b5c3..cb6d8934e 100644
--- a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/RocksDBModule.java
+++ b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/RocksDBModule.java
@@ -10,24 +10,55 @@
import static org.dizitart.no2.common.util.Iterables.setOf;
+/**
+ * A Nitrite store module that provides a RocksDB implementation of the
+ * NitriteStore interface.
+ *
+ * @since 4.0
+ * @see NitriteStore
+ * @see StoreModule
+ * @author Anindya Chatterjee
+ */
public class RocksDBModule implements StoreModule {
@Setter(AccessLevel.PACKAGE)
+ /**
+ * The RocksDB configuration for the Nitrite database store.
+ */
private RocksDBConfig storeConfig;
+ /**
+ * Instantiates a new RocksDB module.
+ */
public RocksDBModule(String path) {
this.storeConfig = new RocksDBConfig();
this.storeConfig.filePath(path);
}
+ /**
+ * Returns a set of Nitrite plugins.
+ *
+ * @return a set of Nitrite plugins.
+ */
@Override
public Set plugins() {
return setOf(getStore());
}
+ /**
+ * Returns a new instance of {@link RocksDBModuleBuilder} to build a
+ * {@link RocksDBModule} with custom configuration.
+ *
+ * @return a new instance of {@link RocksDBModuleBuilder}.
+ */
public static RocksDBModuleBuilder withConfig() {
return new RocksDBModuleBuilder();
}
+ /**
+ * Returns a new instance of {@link NitriteStore} backed by RocksDB.
+ *
+ * @return a new instance of {@link NitriteStore} backed by RocksDB.
+ */
public NitriteStore> getStore() {
RocksDBStore store = new RocksDBStore();
store.setStoreConfig(storeConfig);
diff --git a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/RocksDBModuleBuilder.java b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/RocksDBModuleBuilder.java
index 8de08a377..20f9def6b 100644
--- a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/RocksDBModuleBuilder.java
+++ b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/RocksDBModuleBuilder.java
@@ -31,17 +31,39 @@
import java.util.Set;
/**
+ * A builder class to create a RocksDBModule instance with the desired configuration.
+ *
+ * @since 4.0
+ * @see RocksDBModule
* @author Anindya Chatterjee
*/
@Getter
@Setter
@Accessors(fluent = true)
public class RocksDBModuleBuilder {
+ /**
+ * The file path of the RocksDB data store.
+ */
private String filePath;
+ /**
+ * The RocksDB {@link Options} used by the module builder.
+ */
private Options options;
+ /**
+ * The RocksDB {@link DBOptions} used by the module builder.
+ */
private DBOptions dbOptions;
+ /**
+ * The RocksDB {@link ColumnFamilyOptions} used by the module builder.
+ */
private ColumnFamilyOptions columnFamilyOptions;
+ /**
+ * The object formatter used to serialize and deserialize objects.
+ */
private ObjectFormatter objectFormatter;
+ /**
+ * The RocksDB configuration for the module.
+ */
private RocksDBConfig dbConfig;
@Setter(AccessLevel.NONE)
@@ -52,6 +74,12 @@ public class RocksDBModuleBuilder {
eventListeners = new HashSet<>();
}
+ /**
+ * Sets the file path for the RocksDB data store.
+ *
+ * @param file the file path for the RocksDB data store.
+ * @return the {@link RocksDBModuleBuilder} instance.
+ */
public RocksDBModuleBuilder filePath(File file) {
if (file != null) {
this.filePath = file.getPath();
@@ -59,16 +87,33 @@ public RocksDBModuleBuilder filePath(File file) {
return this;
}
+ /**
+ * Sets the file path for the RocksDB data store.
+ *
+ * @param path the file path for the RocksDB data store.
+ * @return the current {@link RocksDBModuleBuilder} instance.
+ */
public RocksDBModuleBuilder filePath(String path) {
this.filePath = path;
return this;
}
+ /**
+ * Adds a {@link StoreEventListener} to the module builder.
+ *
+ * @param listener the listener to add
+ * @return the {@link RocksDBModuleBuilder} instance
+ */
public RocksDBModuleBuilder addStoreEventListener(StoreEventListener listener) {
eventListeners.add(listener);
return this;
}
+ /**
+ * Builds a {@link RocksDBModule} with the specified configuration.
+ *
+ * @return the {@link RocksDBModule} instance.
+ */
public RocksDBModule build() {
RocksDBModule module = new RocksDBModule(filePath());
diff --git a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/RocksDBRTree.java b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/RocksDBRTree.java
index 0c2534059..0f760ca83 100644
--- a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/RocksDBRTree.java
+++ b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/RocksDBRTree.java
@@ -29,6 +29,7 @@
import java.util.concurrent.atomic.AtomicBoolean;
/**
+ * @since 4.0
* @author Anindya Chatterjee
*/
public class RocksDBRTree implements NitriteRTree {
diff --git a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/RocksDBReference.java b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/RocksDBReference.java
index 3bdd886e2..66414c6f6 100644
--- a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/RocksDBReference.java
+++ b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/RocksDBReference.java
@@ -30,9 +30,10 @@
import java.util.concurrent.ConcurrentHashMap;
/**
+ * @since 4.0
* @author Anindya Chatterjee
*/
-@Slf4j
+@Slf4j(topic = "nitrite-rocksdb")
@Getter
@Setter
public class RocksDBReference implements AutoCloseable {
diff --git a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/RocksDBStore.java b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/RocksDBStore.java
index 7cb929c91..15f823a43 100644
--- a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/RocksDBStore.java
+++ b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/RocksDBStore.java
@@ -18,7 +18,11 @@
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
-@Slf4j
+/**
+ * @since 4.0
+ * @author Anindya Chatterjee
+ */
+@Slf4j(topic = "nitrite-rocksdb")
public class RocksDBStore extends AbstractNitriteStore {
private final AtomicBoolean closed;
private final Map> nitriteMapRegistry;
diff --git a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/RocksDBStoreUtils.java b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/RocksDBStoreUtils.java
index 7b071c64c..62b7aa950 100644
--- a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/RocksDBStoreUtils.java
+++ b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/RocksDBStoreUtils.java
@@ -1,11 +1,13 @@
package org.dizitart.no2.rocksdb;
-import lombok.extern.slf4j.Slf4j;
import org.dizitart.no2.exceptions.InvalidOperationException;
import static org.dizitart.no2.common.util.StringUtils.isNullOrEmpty;
-@Slf4j
+/**
+ * @since 4.0
+ * @author Anindya Chatterjee
+ */
class RocksDBStoreUtils {
private RocksDBStoreUtils() {
}
diff --git a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/StoreFactory.java b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/StoreFactory.java
index a7f86e175..0a4a5ad5a 100644
--- a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/StoreFactory.java
+++ b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/StoreFactory.java
@@ -28,9 +28,10 @@
import java.util.concurrent.ConcurrentHashMap;
/**
+ * @since 4.0
* @author Anindya Chatterjee
*/
-@Slf4j(topic = "no2-rocksdb")
+@Slf4j(topic = "nitrite-rocksdb")
class StoreFactory {
private StoreFactory() {
}
diff --git a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/ValueSet.java b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/ValueSet.java
index 3916a5e1d..50a316937 100644
--- a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/ValueSet.java
+++ b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/ValueSet.java
@@ -10,6 +10,10 @@
import static org.dizitart.no2.rocksdb.Constants.CLEANER;
+/**
+ * @since 4.0
+ * @author Anindya Chatterjee
+ */
class ValueSet implements Iterable {
private final ObjectFormatter objectFormatter;
private final RocksDB rocksDB;
diff --git a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/formatter/ComparableKeySerializer.java b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/formatter/ComparableKeySerializer.java
index 747571769..c24c6c751 100644
--- a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/formatter/ComparableKeySerializer.java
+++ b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/formatter/ComparableKeySerializer.java
@@ -6,6 +6,7 @@
import com.esotericsoftware.kryo.kryo5.io.Output;
/**
+ * @since 4.0
* @author Anindya Chatterjee
*/
public abstract class ComparableKeySerializer> extends KryoKeySerializer {
diff --git a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/formatter/DefaultJavaSerializers.java b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/formatter/DefaultJavaSerializers.java
index 6dc8ca5bd..3091d0092 100644
--- a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/formatter/DefaultJavaSerializers.java
+++ b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/formatter/DefaultJavaSerializers.java
@@ -8,6 +8,7 @@
import java.util.UUID;
/**
+ * @since 4.0
* @author Anindya Chatterjee
*/
public class DefaultJavaSerializers {
diff --git a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/formatter/DefaultTimeKeySerializers.java b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/formatter/DefaultTimeKeySerializers.java
index 097817233..172d413fc 100644
--- a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/formatter/DefaultTimeKeySerializers.java
+++ b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/formatter/DefaultTimeKeySerializers.java
@@ -13,6 +13,7 @@
import java.util.Locale;
/**
+ * @since 4.0
* @author Anindya Chatterjee
*/
class DefaultTimeKeySerializers {
diff --git a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/formatter/KryoKeySerializer.java b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/formatter/KryoKeySerializer.java
index a9a594f3a..5d9c34b54 100644
--- a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/formatter/KryoKeySerializer.java
+++ b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/formatter/KryoKeySerializer.java
@@ -7,6 +7,7 @@
import com.esotericsoftware.kryo.kryo5.io.Output;
/**
+ * @since 4.0
* @author Anindya Chatterjee
*/
public abstract class KryoKeySerializer extends Serializer {
diff --git a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/formatter/KryoObjectFormatter.java b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/formatter/KryoObjectFormatter.java
index 29d1a392c..58b33ca1b 100644
--- a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/formatter/KryoObjectFormatter.java
+++ b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/formatter/KryoObjectFormatter.java
@@ -34,9 +34,10 @@
import static org.dizitart.no2.rocksdb.Constants.DB_NULL;
/**
+ * @since 4.0
* @author Anindya Chatterjee
*/
-@Slf4j
+@Slf4j(topic = "nitrite-rocksdb")
public class KryoObjectFormatter implements ObjectFormatter {
private static final Kryo kryo = new Kryo();
private final Map, KryoKeySerializer>> keySerializerRegistry;
diff --git a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/formatter/NitriteSerializers.java b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/formatter/NitriteSerializers.java
index d570520a8..acc1cdc73 100644
--- a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/formatter/NitriteSerializers.java
+++ b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/formatter/NitriteSerializers.java
@@ -24,6 +24,7 @@
import java.util.concurrent.atomic.AtomicBoolean;
/**
+ * @since 4.0
* @author Anindya Chatterjee
*/
public class NitriteSerializers {
diff --git a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/formatter/ObjectFormatter.java b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/formatter/ObjectFormatter.java
index 8f6a8cd30..82863e498 100644
--- a/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/formatter/ObjectFormatter.java
+++ b/nitrite-rocksdb-adapter/src/main/java/org/dizitart/no2/rocksdb/formatter/ObjectFormatter.java
@@ -16,13 +16,50 @@
package org.dizitart.no2.rocksdb.formatter;
+
/**
+ * An interface to define methods for encoding and decoding objects and their
+ * keys.
+ *
+ * @since 4.0
* @author Anindya Chatterjee
*/
public interface ObjectFormatter {
+ /**
+ * Encodes an object into a byte array.
+ *
+ * @param object the object to encode
+ * @param the type of the object
+ * @return the byte array representing the encoded object
+ */
byte[] encode(T object);
+
+ /**
+ * Encodes an object's key into a byte array.
+ *
+ * @param object the object whose key to encode
+ * @param the type of the object
+ * @return the byte array representing the encoded key
+ */
byte[] encodeKey(T object);
+ /**
+ * Decodes a byte array into an object of the specified type.
+ *
+ * @param bytes the byte array to decode
+ * @param type the type of the object to decode
+ * @param the type of the object
+ * @return the decoded object
+ */
T decode(byte[] bytes, Class type);
+
+ /**
+ * Decodes a byte array into an object's key of the specified type.
+ *
+ * @param bytes the byte array to decode
+ * @param type the type of the object's key to decode
+ * @param the type of the object's key
+ * @return the decoded object's key
+ */
T decodeKey(byte[] bytes, Class type);
}
diff --git a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/NitriteTest.java b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/NitriteTest.java
index 856d162e2..c2be82757 100644
--- a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/NitriteTest.java
+++ b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/NitriteTest.java
@@ -20,16 +20,16 @@
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
import org.dizitart.no2.collection.Document;
import org.dizitart.no2.collection.FindOptions;
import org.dizitart.no2.collection.NitriteCollection;
import org.dizitart.no2.collection.UpdateOptions;
import org.dizitart.no2.common.SortOrder;
-import org.dizitart.no2.common.WriteResult;
import org.dizitart.no2.common.concurrent.ThreadPoolManager;
import org.dizitart.no2.common.mapper.EntityConverter;
+import org.dizitart.no2.common.mapper.SimpleNitriteMapper;
import org.dizitart.no2.common.mapper.NitriteMapper;
-import org.dizitart.no2.common.mapper.SimpleDocumentMapper;
import org.dizitart.no2.exceptions.NitriteIOException;
import org.dizitart.no2.exceptions.ValidationException;
import org.dizitart.no2.index.IndexOptions;
@@ -69,6 +69,7 @@
/**
* @author Anindya Chatterjee.
*/
+@Slf4j
public class NitriteTest {
private Nitrite db;
private NitriteCollection collection;
@@ -82,10 +83,10 @@ public class NitriteTest {
public void setUp() throws ParseException {
db = TestUtil.createDb(fileName, "test-user", "test-password");
- SimpleDocumentMapper simpleDocumentMapper = (SimpleDocumentMapper) db.getConfig().nitriteMapper();
- simpleDocumentMapper.registerEntityConverter(new Receipt.Converter());
- simpleDocumentMapper.registerEntityConverter(new CompatChild.Converter());
- simpleDocumentMapper.registerEntityConverter(new EmptyClass.Converter());
+ SimpleNitriteMapper simpleNitriteMapper = (SimpleNitriteMapper) db.getConfig().nitriteMapper();
+ simpleNitriteMapper.registerEntityConverter(new Receipt.Converter());
+ simpleNitriteMapper.registerEntityConverter(new CompatChild.Converter());
+ simpleNitriteMapper.registerEntityConverter(new EmptyClass.Converter());
simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
@@ -330,7 +331,7 @@ public void testIssue185() throws InterruptedException {
} catch (InterruptedException ignored) {
}
} catch (Throwable t) {
- t.printStackTrace();
+ log.error("Error while updating", t);
}
}
latch.countDown();
@@ -364,7 +365,7 @@ public void testIssue193() throws InterruptedException {
receipt.setClientRef(refs[refIndex]);
repository.update(receipt, true);
} catch (Exception e) {
- e.printStackTrace();
+ log.error("Error while updating", e);
fail("Unhandled exception in thread - " + e.getMessage());
} finally {
latch.countDown();
@@ -396,7 +397,7 @@ public void testIssue212() {
doc, UpdateOptions.updateOptions(true));
for (Document document : collection.find()) {
- System.out.println(document);
+ assertNotNull(document);
}
}
@@ -410,14 +411,8 @@ public void run() {
NitriteCollection collection = db.getCollection("testIssue245");
for (int i = 0; i < 5; i++) {
-
- System.out.println("Thread ID = " + id + " Inserting doc " + i);
Document doc = Document.createDocument(UUID.randomUUID().toString(), UUID.randomUUID().toString());
-
- WriteResult result = collection.insert(doc);//db.commit();
- System.out.println("Result of insert = " + result.getAffectedCount());
- System.out.println("Thread id = " + id + " --> count = " + collection.size());
-
+ collection.insert(doc);//db.commit();
Thread.sleep(10);
}//for closing
@@ -425,7 +420,7 @@ public void run() {
collection.close();
} catch (Throwable e) {
- e.printStackTrace();
+ log.error("Error while running thread", e);
}
}
};
@@ -445,7 +440,6 @@ public void run() {
t2.join();
NitriteCollection collection = db.getCollection("testIssue245");
- System.out.println("No of Documents = " + collection.size());
collection.close();
db.close();
}
diff --git a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/MultiThreadedTest.java b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/MultiThreadedTest.java
index 16dc19ca3..33b526136 100644
--- a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/MultiThreadedTest.java
+++ b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/MultiThreadedTest.java
@@ -17,6 +17,7 @@
package org.dizitart.no2.integration;
+import lombok.extern.slf4j.Slf4j;
import org.dizitart.no2.Nitrite;
import org.dizitart.no2.collection.Document;
import org.dizitart.no2.collection.DocumentCursor;
@@ -46,6 +47,7 @@
/**
* @author Anindya Chatterjee.
*/
+@Slf4j
public class MultiThreadedTest {
private static final String fileName = TestUtil.getRandomTempDbFile();
private NitriteCollection collection;
@@ -99,9 +101,7 @@ public void testOperations() throws InterruptedException {
assertTrue(collection.hasIndex("unixTime"));
} catch (Throwable e) {
- System.out.println("Exception at thread " +
- Thread.currentThread().getName() + " with iteration " + j);
- e.printStackTrace();
+ log.error("Error while executing test", e);
}
}
latch.countDown();
diff --git a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/NitriteBuilderTest.java b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/NitriteBuilderTest.java
index 058e0b36b..de615b29e 100644
--- a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/NitriteBuilderTest.java
+++ b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/NitriteBuilderTest.java
@@ -29,7 +29,7 @@
import org.dizitart.no2.common.Fields;
import org.dizitart.no2.common.mapper.EntityConverter;
import org.dizitart.no2.common.mapper.NitriteMapper;
-import org.dizitart.no2.common.mapper.SimpleDocumentMapper;
+import org.dizitart.no2.common.mapper.SimpleNitriteMapper;
import org.dizitart.no2.exceptions.InvalidOperationException;
import org.dizitart.no2.exceptions.NitriteIOException;
import org.dizitart.no2.exceptions.NitriteSecurityException;
@@ -175,7 +175,7 @@ public void testPopulateRepositories() {
.fieldSeparator(".")
.openOrCreate();
- SimpleDocumentMapper documentMapper = (SimpleDocumentMapper) db.getConfig().nitriteMapper();
+ SimpleNitriteMapper documentMapper = (SimpleNitriteMapper) db.getConfig().nitriteMapper();
documentMapper.registerEntityConverter(new TestObject.Converter());
documentMapper.registerEntityConverter(new TestObject2.Converter());
diff --git a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/NitriteStressTest.java b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/NitriteStressTest.java
index ff2d6dd9d..c1dca3c58 100644
--- a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/NitriteStressTest.java
+++ b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/NitriteStressTest.java
@@ -20,13 +20,14 @@
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlSchemaType;
import lombok.Data;
+import lombok.extern.slf4j.Slf4j;
import org.dizitart.no2.Nitrite;
import org.dizitart.no2.collection.Document;
import org.dizitart.no2.collection.DocumentCursor;
import org.dizitart.no2.collection.NitriteCollection;
import org.dizitart.no2.common.mapper.EntityConverter;
import org.dizitart.no2.common.mapper.NitriteMapper;
-import org.dizitart.no2.common.mapper.SimpleDocumentMapper;
+import org.dizitart.no2.common.mapper.SimpleNitriteMapper;
import org.dizitart.no2.filters.Filter;
import org.dizitart.no2.index.IndexOptions;
import org.dizitart.no2.index.IndexType;
@@ -54,6 +55,7 @@
/**
* @author Anindya Chatterjee
*/
+@Slf4j
public class NitriteStressTest {
private static final int TEST_SET_COUNT = 15000;
private final PodamFactory podamFactory = new PodamFactoryImpl();
@@ -67,13 +69,12 @@ public class NitriteStressTest {
@Before
public void before() {
db = createDb(fileName);
- SimpleDocumentMapper documentMapper = (SimpleDocumentMapper) db.getConfig().nitriteMapper();
+ SimpleNitriteMapper documentMapper = (SimpleNitriteMapper) db.getConfig().nitriteMapper();
documentMapper.registerEntityConverter(new TestDto.Converter());
documentMapper.registerEntityConverter(new PerfTest.Converter());
documentMapper.registerEntityConverter(new PerfTestIndexed.Converter());
collection = db.getCollection("test");
- System.out.println(fileName);
}
@After
@@ -81,7 +82,6 @@ public void cleanUp() {
if (db != null && !db.isClosed()) {
long start = System.currentTimeMillis();
db.close();
- System.out.println("Time to compact and close - " + (System.currentTimeMillis() - start) / 1000 + " seconds");
}
deleteDb(fileName);
@@ -100,7 +100,7 @@ public void stressTest() {
counter++;
}
} catch (Throwable t) {
- System.err.println("Crashed after " + counter + " records");
+ log.error("Error inserting record", t);
throw t;
}
@@ -118,38 +118,22 @@ public void testIssue41() {
AtomicLong counter = new AtomicLong(System.currentTimeMillis());
PodamFactory factory = new PodamFactoryImpl();
- long start = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
Document doc = Document.createDocument();
doc.put("number", random.nextDouble());
doc.put("name", factory.manufacturePojo(String.class));
doc.put("counter", counter.getAndIncrement());
collection.insert(doc);
- if (i % 10000 == 0) {
- System.out.println(i + " entries written");
- }
}
- System.out.println("Records inserted in " + ((System.currentTimeMillis() - start) / (1000 * 60)) + " minutes");
if (db.hasUnsavedChanges()) {
db.commit();
}
- start = System.currentTimeMillis();
DocumentCursor cursor = collection.find();
- System.out.println("Size ->" + cursor.size());
- System.out.println("Records size calculated in " + ((System.currentTimeMillis() - start) / (1000)) + " seconds");
-
- int i = 0;
- start = System.currentTimeMillis();
for (Document element : cursor) {
assertNotNull(element);
- i++;
- if (i % 10000 == 0) {
- System.out.println(i + " entries processed");
- }
}
- System.out.println("Iteration completed in " + ((System.currentTimeMillis() - start) / (1000)) + " seconds");
}
@Test
@@ -166,17 +150,11 @@ public void testRepoPerformanceWithIndex() {
// actual calculation
repo = db.getRepository(PerfTestIndexed.class);
- long start = System.currentTimeMillis();
for (PerfTestIndexed item : items) {
repo.insert(item);
}
- long diff = System.currentTimeMillis() - start;
- System.out.println("Time take to insert 10000 indexed items - " + diff + "ms");
- start = System.currentTimeMillis();
repo.remove(Filter.ALL);
- diff = System.currentTimeMillis() - start;
- System.out.println("Time take to remove 10000 indexed items - " + diff + "ms");
}
@Test
@@ -193,17 +171,11 @@ public void testRepoPerformanceWithoutIndex() {
// actual calculation
repo = db.getRepository(PerfTest.class);
- long start = System.currentTimeMillis();
for (PerfTest item : items) {
repo.insert(item);
}
- long diff = System.currentTimeMillis() - start;
- System.out.println("Time take to insert 10000 non-indexed items - " + diff + "ms");
- start = System.currentTimeMillis();
repo.remove(Filter.ALL);
- diff = System.currentTimeMillis() - start;
- System.out.println("Time take to remove 10000 non-indexed items - " + diff + "ms");
}
private List createTestSet() {
diff --git a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/NitriteTest.java b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/NitriteTest.java
index 20c06f02c..317a43ce6 100644
--- a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/NitriteTest.java
+++ b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/NitriteTest.java
@@ -19,7 +19,7 @@
import org.dizitart.no2.Nitrite;
import org.dizitart.no2.collection.NitriteCollection;
-import org.dizitart.no2.common.mapper.SimpleDocumentMapper;
+import org.dizitart.no2.common.mapper.SimpleNitriteMapper;
import org.dizitart.no2.integration.repository.data.ClassA;
import org.dizitart.no2.integration.repository.data.ClassBConverter;
import org.junit.After;
@@ -39,7 +39,7 @@ public class NitriteTest {
@Before
public void setUp() {
db = createDb(fileName);
- SimpleDocumentMapper nitriteMapper = (SimpleDocumentMapper) db.getConfig().nitriteMapper();
+ SimpleNitriteMapper nitriteMapper = (SimpleNitriteMapper) db.getConfig().nitriteMapper();
nitriteMapper.registerEntityConverter(new ClassA.ClassAConverter());
nitriteMapper.registerEntityConverter(new ClassBConverter());
diff --git a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/Retry.java b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/Retry.java
index 3d6a27d11..a25ef04b1 100644
--- a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/Retry.java
+++ b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/Retry.java
@@ -17,6 +17,7 @@
package org.dizitart.no2.integration;
+import lombok.extern.slf4j.Slf4j;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
@@ -24,6 +25,7 @@
/**
* @author Anindya Chatterjee
*/
+@Slf4j
public class Retry implements TestRule {
private final int retryCount;
@@ -48,11 +50,13 @@ public void evaluate() throws Throwable {
return;
} catch (Throwable t) {
caughtThrowable = t;
- System.err.println(description.getDisplayName() + ": run " + (i + 1) + " failed");
+ log.error(description.getDisplayName() + ": run " + (i + 1) + " failed");
}
}
- System.err.println(description.getDisplayName() + ": giving up after " + retryCount + " failures");
- throw caughtThrowable;
+ log.error(description.getDisplayName() + ": giving up after " + retryCount + " failures");
+ if (caughtThrowable != null) {
+ throw caughtThrowable;
+ }
}
};
}
diff --git a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/SerializabilityTest.java b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/SerializabilityTest.java
index 09ca50080..9f0bf35a6 100644
--- a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/SerializabilityTest.java
+++ b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/SerializabilityTest.java
@@ -18,6 +18,7 @@
package org.dizitart.no2.integration;
import lombok.Data;
+import lombok.extern.slf4j.Slf4j;
import org.dizitart.no2.Nitrite;
import org.dizitart.no2.collection.Document;
import org.dizitart.no2.collection.NitriteCollection;
@@ -33,6 +34,7 @@
/**
* @author Anindya Chatterjee
*/
+@Slf4j
public class SerializabilityTest {
private NitriteCollection collection;
private File dbFile;
@@ -69,9 +71,8 @@ public void testSerializabilityValidation() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
- e.printStackTrace();
+ log.error("Error while sleeping", e);
}
- System.out.println("Write " + i + " completed");
}
}
@@ -85,9 +86,8 @@ public void testSerializablity() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
- e.printStackTrace();
+ log.error("Error while sleeping", e);
}
- System.out.println("Write " + i + " completed");
}
}
diff --git a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/TestUtil.java b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/TestUtil.java
index 5d1689ef4..e51892291 100644
--- a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/TestUtil.java
+++ b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/TestUtil.java
@@ -22,7 +22,6 @@
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
-import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.dizitart.no2.Nitrite;
@@ -51,10 +50,13 @@ public static String getRandomTempDbFile() {
return file.getPath() + File.separator + UUID.randomUUID() + ".db";
}
- @SneakyThrows
public static void deleteDb(String fileName) {
- File file = new File(fileName);
- FileUtils.deleteDirectory(file);
+ try {
+ File file = new File(fileName);
+ FileUtils.deleteDirectory(file);
+ } catch (Exception e) {
+ log.error("Error while deleting db", e);
+ }
}
public static > boolean isSorted(Iterable iterable, boolean ascending) {
diff --git a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/collection/CollectionCompoundIndexTest.java b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/collection/CollectionCompoundIndexTest.java
index 8d37792ed..ffa990763 100644
--- a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/collection/CollectionCompoundIndexTest.java
+++ b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/collection/CollectionCompoundIndexTest.java
@@ -25,6 +25,7 @@
import org.dizitart.no2.common.WriteResult;
import org.dizitart.no2.filters.Filter;
import org.dizitart.no2.index.IndexType;
+import org.junit.Assert;
import org.junit.Test;
import java.util.Date;
@@ -151,7 +152,7 @@ public void testDeleteWithIndex() {
@Test
public void testRebuildIndexOnRunningIndex() {
insert();
- db.getStore().subscribe(System.out::println);
+ db.getStore().subscribe(Assert::assertNotNull);
collection.createIndex("firstName", "lastName");
collection.rebuildIndex("firstName", "lastName");
diff --git a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/collection/CollectionIndexTest.java b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/collection/CollectionIndexTest.java
index 4a45fa055..28a09d17d 100644
--- a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/collection/CollectionIndexTest.java
+++ b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/collection/CollectionIndexTest.java
@@ -278,7 +278,6 @@ public void testIndexEvent() {
break;
}
assertTrue(eventInfo.getItem() instanceof String);
- System.out.println(eventInfo.getEventType() + " for field " + eventInfo.getItem());
});
collection.createIndex(indexOptions(IndexType.NON_UNIQUE), "first");
diff --git a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/collection/CollectionJoinTest.java b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/collection/CollectionJoinTest.java
index caff44d61..3085b3625 100644
--- a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/collection/CollectionJoinTest.java
+++ b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/collection/CollectionJoinTest.java
@@ -100,7 +100,6 @@ public void testJoinAll() {
} else if (document.get("firstName") == "fn3") {
assertNull(document.get("personalDetails"));
}
- System.out.println(document);
}
}
}
diff --git a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/collection/CollectionUpdateTest.java b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/collection/CollectionUpdateTest.java
index 86bff59b5..4dad51555 100644
--- a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/collection/CollectionUpdateTest.java
+++ b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/collection/CollectionUpdateTest.java
@@ -214,7 +214,6 @@ public void updateAfterAttributeRemoval() {
assertEquals(savedDoc1, clonedDoc1);
clonedDoc1.put("group", null);
-// clonedDoc1.remove("group");
assertEquals(1, coll.update(clonedDoc1).getAffectedCount());
Document savedDoc2 = coll.find(Filter.ALL).firstOrNull();
@@ -222,6 +221,38 @@ public void updateAfterAttributeRemoval() {
assertNull(savedDoc2.get("group"));
}
+ @Test
+ public void updateNestedDocument() {
+ // github issue - 704
+ Document doc1 = createDocument("conversation",
+ createDocument("unread",
+ createDocument("me", 1).put("other", 2)));
+ Document doc2 = createDocument("conversation",
+ createDocument("unread",
+ createDocument("me", 10).put("other", 4)));
+
+ NitriteCollection coll = db.getCollection("test_updateNestedDocument");
+ coll.remove(Filter.ALL);
+ coll.insert(doc1, doc2);
+
+ DocumentCursor cursor = coll.find(where("conversation.unread.me").gt(5));
+ assertEquals(cursor.size(), 1);
+
+ Document update = createDocument("conversation",
+ createDocument("unread",
+ createDocument("me", 0)));
+ coll.update(Filter.ALL, update);
+
+ cursor = coll.find(where("conversation.unread.me").gt(5));
+ assertEquals(cursor.size(), 0);
+
+ cursor = coll.find(where("conversation.unread.other").lt(5));
+ assertEquals(cursor.size(), 2);
+
+ cursor = coll.find(where("conversation.unread.other").lt(5).not());
+ assertEquals(cursor.size(), 0);
+ }
+
@Test(expected = NotIdentifiableException.class)
public void testUpdateWithoutId() {
NitriteCollection collection = db.getCollection("test");
diff --git a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/collection/FieldProcessorTest.java b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/collection/FieldProcessorTest.java
deleted file mode 100644
index 08cf8fc9f..000000000
--- a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/collection/FieldProcessorTest.java
+++ /dev/null
@@ -1,202 +0,0 @@
-/*
- * Copyright (c) 2017-2021 Nitrite author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package org.dizitart.no2.integration.collection;
-
-import org.dizitart.no2.collection.Document;
-import org.dizitart.no2.collection.NitriteCollection;
-import org.dizitart.no2.collection.NitriteId;
-import org.dizitart.no2.common.WriteResult;
-import org.dizitart.no2.common.crypto.AESEncryptor;
-import org.dizitart.no2.common.crypto.Encryptor;
-import org.dizitart.no2.common.processors.Processor;
-import org.dizitart.no2.common.processors.StringFieldEncryptionProcessor;
-import org.dizitart.no2.exceptions.NitriteSecurityException;
-import org.dizitart.no2.store.NitriteMap;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.nio.charset.StandardCharsets;
-import java.util.Date;
-import java.util.List;
-
-import static org.dizitart.no2.common.util.Iterables.toList;
-import static org.dizitart.no2.filters.FluentFilter.where;
-import static org.junit.Assert.*;
-
-/**
- * @author Anindya Chatterjee
- */
-public class FieldProcessorTest extends BaseCollectionTest {
-
- private Encryptor encryptor;
- private NitriteCollection collection;
- private Processor cvvProcessor;
-
- @Before
- public void setUp() {
- super.setUp();
-
- encryptor = new AESEncryptor("s3k4e8");
- cvvProcessor = new Processor() {
- @Override
- public Document processBeforeWrite(Document document) {
- String cvv = document.get("cvv", String.class);
- String encryptedCvv = encryptor.encrypt(cvv.getBytes(StandardCharsets.UTF_8));
- document.put("cvv", encryptedCvv);
- return document;
- }
-
- @Override
- public Document processAfterRead(Document document) {
- String encryptedCvv = document.get("cvv", String.class);
- String cvv = encryptor.decrypt(encryptedCvv);
- document.put("cvv", cvv);
- return document;
- }
- };
- StringFieldEncryptionProcessor creditCardProcessor = new StringFieldEncryptionProcessor(encryptor);
- creditCardProcessor.addFields("creditCardNumber");
-
- collection = db.getCollection("encryption-test");
- collection.addProcessor(creditCardProcessor);
-
- Document document = Document.createDocument("name", "John Doe")
- .put("creditCardNumber", "5548960345687452")
- .put("cvv", "007")
- .put("expiryDate", new Date());
- collection.insert(document);
-
- document = Document.createDocument("name", "Jane Doe")
- .put("creditCardNumber", "5500960345687452")
- .put("cvv", "008")
- .put("expiryDate", new Date());
- collection.insert(document);
-
- cvvProcessor.process(collection);
- collection.addProcessor(cvvProcessor);
- }
-
- @Test
- public void testFieldEncryptionInNitriteMap() {
- NitriteMap nitriteMap = collection.getStore().openMap("encryption-test",
- NitriteId.class, Document.class);
-
- List documents = toList(nitriteMap.values());
- for (Document document : documents) {
- if (document.get("creditCardNumber", String.class).equalsIgnoreCase("5548960345687452")) {
- Assert.fail("unencrypted secret text found");
- }
-
- if (document.get("creditCardNumber", String.class).equalsIgnoreCase("5500960345687452")) {
- Assert.fail("unencrypted secret text found");
- }
-
- if (document.get("cvv", String.class).equalsIgnoreCase("008")) {
- Assert.fail("unencrypted secret text found");
- }
-
- if (document.get("cvv", String.class).equalsIgnoreCase("007")) {
- Assert.fail("unencrypted secret text found");
- }
- }
- }
-
- @Test
- public void testSuccessfulDecryption() {
- Document document = collection.find(where("name").eq("Jane Doe")).firstOrNull();
- assertNotNull(document);
-
- assertEquals(document.get("creditCardNumber", String.class), "5500960345687452");
- assertEquals(document.get("cvv", String.class), "008");
-
- document = collection.find(where("name").eq("John Doe")).firstOrNull();
- assertNotNull(document);
-
- assertEquals(document.get("creditCardNumber", String.class), "5548960345687452");
- assertEquals(document.get("cvv", String.class), "007");
- }
-
- @Test(expected = NitriteSecurityException.class)
- public void testFailedDecryption() {
- Encryptor wrongEncryptor = new AESEncryptor("secret");
-
- collection = db.getCollection("encryption-test");
- collection.addProcessor(new Processor() {
- @Override
- public Document processBeforeWrite(Document document) {
- String creditCardNumber = document.get("creditCardNumber", String.class);
- String encryptedCreditCardNumber = encryptor.encrypt(creditCardNumber.getBytes(StandardCharsets.UTF_8));
- document.put("creditCardNumber", encryptedCreditCardNumber);
- return document;
- }
-
- @Override
- public Document processAfterRead(Document document) {
- String encryptedCreditCardNumber = document.get("creditCardNumber", String.class);
- String creditCardNumber = wrongEncryptor.decrypt(encryptedCreditCardNumber);
- document.put("creditCardNumber", creditCardNumber);
- return document;
- }
- });
-
- Document document = Document.createDocument("name", "John Doe")
- .put("creditCardNumber", "5548960345687452")
- .put("cvv", "007")
- .put("expiryDate", new Date());
- collection.insert(document);
-
- document = Document.createDocument("name", "Jane Doe")
- .put("creditCardNumber", "5500960345687452")
- .put("cvv", "008")
- .put("expiryDate", new Date());
- collection.insert(document);
-
- collection.find(where("name").eq("Jane Doe")).firstOrNull();
- }
-
- @Test
- public void testSearchOnEncryptedField() {
- Document document = collection.find(where("cvv").eq("008")).firstOrNull();
- assertNull(document);
- }
-
- @Test
- public void testUpdateEncryptedField() {
- Document document = Document.createDocument("name", "John Doe")
- .put("creditCardNumber", "00000000000000")
- .put("cvv", "007")
- .put("expiryDate", new Date());
-
- WriteResult writeResult = collection.update(where("name").eq("John Doe"), document);
- assertEquals(writeResult.getAffectedCount(), 1);
-
- document = collection.find(where("name").eq("John Doe")).firstOrNull();
- assertNotNull(document);
-
- assertEquals(document.get("creditCardNumber", String.class), "00000000000000");
- assertEquals(document.get("cvv", String.class), "007");
- }
-
- @Test
- public void testIndexOnEncryptedField() {
- collection.createIndex("cvv");
- Document document = collection.find(where("cvv").eq("008")).firstOrNull();
- assertNull(document);
- }
-}
diff --git a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/event/EventTest.java b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/event/EventTest.java
index 9bbbcbdb1..1d977b58d 100644
--- a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/event/EventTest.java
+++ b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/event/EventTest.java
@@ -19,7 +19,7 @@
import org.dizitart.no2.Nitrite;
import org.dizitart.no2.collection.events.EventType;
-import org.dizitart.no2.common.mapper.SimpleDocumentMapper;
+import org.dizitart.no2.common.mapper.SimpleNitriteMapper;
import org.dizitart.no2.integration.Retry;
import org.dizitart.no2.integration.repository.data.Employee;
import org.dizitart.no2.repository.ObjectRepository;
@@ -88,7 +88,7 @@ public void setUp() {
.openOrCreate();
}
- SimpleDocumentMapper documentMapper = (SimpleDocumentMapper) db.getConfig().nitriteMapper();
+ SimpleNitriteMapper documentMapper = (SimpleNitriteMapper) db.getConfig().nitriteMapper();
documentMapper.registerEntityConverter(new Employee.EmployeeConverter());
employeeRepository = db.getRepository(Employee.class);
@@ -150,7 +150,6 @@ public void testDelete() {
employeeRepository.remove(where("empId").eq(1L));
await().atMost(1, TimeUnit.SECONDS).until(listenerPrepared(EventType.Remove));
- System.out.println("Action - " + listener.getAction());
assertEquals(listener.getAction(), EventType.Remove);
assertNotNull(listener.getItem());
}
diff --git a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/migrate/MigrationTest.java b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/migrate/MigrationTest.java
index cd31138bd..1ea089de0 100644
--- a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/migrate/MigrationTest.java
+++ b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/migrate/MigrationTest.java
@@ -23,7 +23,7 @@
import org.dizitart.no2.collection.NitriteCollection;
import org.dizitart.no2.common.Constants;
import org.dizitart.no2.common.Fields;
-import org.dizitart.no2.common.mapper.SimpleDocumentMapper;
+import org.dizitart.no2.common.mapper.SimpleNitriteMapper;
import org.dizitart.no2.exceptions.MigrationException;
import org.dizitart.no2.index.IndexOptions;
import org.dizitart.no2.index.IndexType;
@@ -58,7 +58,7 @@ public class MigrationTest {
@Before
public void setUp() {
db = createDb(dbPath);
- SimpleDocumentMapper documentMapper = (SimpleDocumentMapper) db.getConfig().nitriteMapper();
+ SimpleNitriteMapper documentMapper = (SimpleNitriteMapper) db.getConfig().nitriteMapper();
documentMapper.registerEntityConverter(new OldClass.Converter());
documentMapper.registerEntityConverter(new OldClass.Literature.Converter());
documentMapper.registerEntityConverter(new NewClass.Converter());
@@ -127,7 +127,7 @@ public void migrate(InstructionSet instruction) {
.addMigrations(migration)
.openOrCreate("test-user", "test-password");
- SimpleDocumentMapper documentMapper = (SimpleDocumentMapper) db.getConfig().nitriteMapper();
+ SimpleNitriteMapper documentMapper = (SimpleNitriteMapper) db.getConfig().nitriteMapper();
documentMapper.registerEntityConverter(new OldClass.Converter());
documentMapper.registerEntityConverter(new OldClass.Literature.Converter());
documentMapper.registerEntityConverter(new NewClass.Converter());
diff --git a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/BaseObjectRepositoryTest.java b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/BaseObjectRepositoryTest.java
index 0f34b6136..9e40324d7 100644
--- a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/BaseObjectRepositoryTest.java
+++ b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/BaseObjectRepositoryTest.java
@@ -19,7 +19,7 @@
import org.dizitart.no2.Nitrite;
import org.dizitart.no2.NitriteBuilder;
-import org.dizitart.no2.common.mapper.SimpleDocumentMapper;
+import org.dizitart.no2.common.mapper.SimpleNitriteMapper;
import org.dizitart.no2.integration.Retry;
import org.dizitart.no2.integration.repository.data.*;
import org.dizitart.no2.integration.repository.decorator.ManufacturerConverter;
@@ -38,7 +38,6 @@
import java.util.Arrays;
import java.util.Collection;
-import static org.dizitart.no2.filters.Filter.ALL;
import static org.dizitart.no2.integration.TestUtil.deleteDb;
import static org.dizitart.no2.integration.TestUtil.getRandomTempDbFile;
@@ -109,7 +108,7 @@ protected void openDb() {
db = nitriteBuilder.openOrCreate();
}
- SimpleDocumentMapper documentMapper = (SimpleDocumentMapper) db.getConfig().nitriteMapper();
+ SimpleNitriteMapper documentMapper = (SimpleNitriteMapper) db.getConfig().nitriteMapper();
documentMapper.registerEntityConverter(new RepositoryJoinTest.Person.Converter());
documentMapper.registerEntityConverter(new RepositoryJoinTest.Address.Converter());
documentMapper.registerEntityConverter(new RepositoryJoinTest.PersonDetails.Converter());
@@ -139,26 +138,6 @@ protected void openDb() {
@After
public void clear() throws Exception {
- if (companyRepository != null && !companyRepository.isDropped()) {
- companyRepository.remove(ALL);
- }
-
- if (employeeRepository != null && !employeeRepository.isDropped()) {
- employeeRepository.remove(ALL);
- }
-
- if (aObjectRepository != null && !aObjectRepository.isDropped()) {
- aObjectRepository.remove(ALL);
- }
-
- if (cObjectRepository != null && !cObjectRepository.isDropped()) {
- cObjectRepository.remove(ALL);
- }
-
- if (bookRepository != null && !bookRepository.isDropped()) {
- bookRepository.remove(ALL);
- }
-
if (db != null && !db.isClosed()) {
db.commit();
db.close();
diff --git a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/CustomFieldSeparatorTest.java b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/CustomFieldSeparatorTest.java
index 792ac0426..80c1dd974 100644
--- a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/CustomFieldSeparatorTest.java
+++ b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/CustomFieldSeparatorTest.java
@@ -26,7 +26,7 @@
import org.dizitart.no2.collection.Document;
import org.dizitart.no2.common.mapper.EntityConverter;
import org.dizitart.no2.common.mapper.NitriteMapper;
-import org.dizitart.no2.common.mapper.SimpleDocumentMapper;
+import org.dizitart.no2.common.mapper.SimpleNitriteMapper;
import org.dizitart.no2.index.IndexType;
import org.dizitart.no2.integration.Retry;
import org.dizitart.no2.integration.repository.data.Company;
@@ -71,7 +71,7 @@ public void setUp() {
.fieldSeparator(":")
.openOrCreate();
- SimpleDocumentMapper mapper = (SimpleDocumentMapper) db.getConfig().nitriteMapper();
+ SimpleNitriteMapper mapper = (SimpleNitriteMapper) db.getConfig().nitriteMapper();
mapper.registerEntityConverter(new Company.CompanyConverter());
mapper.registerEntityConverter(new EmployeeForCustomSeparator.EmployeeForCustomSeparatorConverter());
mapper.registerEntityConverter(new Note.NoteConverter());
diff --git a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/FieldProcessorTest.java b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/FieldProcessorTest.java
deleted file mode 100644
index 8f31d6408..000000000
--- a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/FieldProcessorTest.java
+++ /dev/null
@@ -1,194 +0,0 @@
-/*
- * Copyright (c) 2017-2021 Nitrite author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package org.dizitart.no2.integration.repository;
-
-import org.dizitart.no2.integration.repository.data.EncryptedPerson;
-import org.dizitart.no2.collection.Document;
-import org.dizitart.no2.collection.NitriteId;
-import org.dizitart.no2.common.WriteResult;
-import org.dizitart.no2.common.crypto.AESEncryptor;
-import org.dizitart.no2.common.crypto.Encryptor;
-import org.dizitart.no2.common.processors.Processor;
-import org.dizitart.no2.common.processors.StringFieldEncryptionProcessor;
-import org.dizitart.no2.exceptions.NitriteSecurityException;
-import org.dizitart.no2.repository.ObjectRepository;
-import org.dizitart.no2.store.NitriteMap;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.nio.charset.StandardCharsets;
-import java.util.Date;
-import java.util.List;
-
-import static org.dizitart.no2.common.util.Iterables.toList;
-import static org.dizitart.no2.common.util.ObjectUtils.findRepositoryName;
-import static org.dizitart.no2.filters.FluentFilter.where;
-import static org.junit.Assert.*;
-
-/**
- * @author Anindya Chatterjee
- */
-public class FieldProcessorTest extends BaseObjectRepositoryTest {
- private ObjectRepository persons;
- private StringFieldEncryptionProcessor fieldProcessor;
-
- @Before
- public void setUp() {
- super.setUp();
- persons = db.getRepository(EncryptedPerson.class);
- fieldProcessor = new StringFieldEncryptionProcessor("s3k4e8");
- fieldProcessor.addFields("creditCardNumber", "cvv");
-
- EncryptedPerson person = new EncryptedPerson();
- person.setName("John Doe");
- person.setCreditCardNumber("5548960345687452");
- person.setCvv("007");
- person.setExpiryDate(new Date());
-
- persons.insert(person);
-
- // process existing data
- fieldProcessor.process(persons);
-
- // add for further changes
- persons.addProcessor(fieldProcessor);
-
- person = new EncryptedPerson();
- person.setName("Jane Doe");
- person.setCreditCardNumber("5500960345687452");
- person.setCvv("008");
- person.setExpiryDate(new Date());
- persons.insert(person);
- }
-
- @Test
- public void testFieldEncryptionInNitriteMap() {
- NitriteMap nitriteMap = persons.getDocumentCollection().getStore()
- .openMap(findRepositoryName(EncryptedPerson.class, null), NitriteId.class, Document.class);
-
- List documents = toList(nitriteMap.values());
- for (Document document : documents) {
- if (document.get("creditCardNumber", String.class).equalsIgnoreCase("5548960345687452")) {
- Assert.fail("unencrypted secret text found");
- }
-
- if (document.get("creditCardNumber", String.class).equalsIgnoreCase("5500960345687452")) {
- Assert.fail("unencrypted secret text found");
- }
-
- if (document.get("cvv", String.class).equalsIgnoreCase("008")) {
- Assert.fail("unencrypted secret text found");
- }
-
- if (document.get("cvv", String.class).equalsIgnoreCase("007")) {
- Assert.fail("unencrypted secret text found");
- }
- }
- }
-
- @Test
- public void testSuccessfulDecryption() {
- EncryptedPerson person = persons.find(where("name").eq("Jane Doe")).firstOrNull();
- assertNotNull(person);
-
- assertEquals(person.getCreditCardNumber(), "5500960345687452");
- assertEquals(person.getCvv(), "008");
-
- person = persons.find(where("name").eq("John Doe")).firstOrNull();
- assertNotNull(person);
-
- assertEquals(person.getCreditCardNumber(), "5548960345687452");
- assertEquals(person.getCvv(), "007");
- }
-
- @Test(expected = NitriteSecurityException.class)
- public void testFailedDecryption() {
- ObjectRepository testPersons = db.getRepository(EncryptedPerson.class, "test");
-
- Encryptor encryptor = new AESEncryptor("secret");
- Encryptor wrongEncryptor = new AESEncryptor("secret", "AES/GCM/NoPadding",
- 5, 5, 5);
-
- testPersons.addProcessor(new Processor() {
- @Override
- public Document processBeforeWrite(Document document) {
- String creditCardNumber = document.get("creditCardNumber", String.class);
- String encryptedCreditCardNumber = encryptor.encrypt(creditCardNumber.getBytes(StandardCharsets.UTF_8));
- document.put("creditCardNumber", encryptedCreditCardNumber);
- return document;
- }
-
- @Override
- public Document processAfterRead(Document document) {
- String encryptedCreditCardNumber = document.get("creditCardNumber", String.class);
- String creditCardNumber = wrongEncryptor.decrypt(encryptedCreditCardNumber);
- document.put("creditCardNumber", creditCardNumber);
- return document;
- }
- });
-
- EncryptedPerson person = new EncryptedPerson();
- person.setName("John Doe");
- person.setCreditCardNumber("5548960345687452");
- person.setCvv("007");
- person.setExpiryDate(new Date());
-
- testPersons.insert(person);
-
- person = new EncryptedPerson();
- person.setName("Jane Doe");
- person.setCreditCardNumber("5500960345687452");
- person.setCvv("008");
- person.setExpiryDate(new Date());
- testPersons.insert(person);
-
- testPersons.find(where("name").eq("Jane Doe")).firstOrNull();
- }
-
- @Test
- public void testSearchOnEncryptedField() {
- EncryptedPerson person = persons.find(where("cvv").eq("008")).firstOrNull();
- assertNull(person);
- }
-
- @Test
- public void testUpdateEncryptedField() {
- EncryptedPerson person = new EncryptedPerson();
- person.setName("John Doe");
- person.setCreditCardNumber("00000000000000");
- person.setCvv("007");
- person.setExpiryDate(new Date());
-
- WriteResult writeResult = persons.update(where("name").eq("John Doe"), person);
- assertEquals(writeResult.getAffectedCount(), 1);
-
- person = persons.find(where("name").eq("John Doe")).firstOrNull();
- assertNotNull(person);
-
- assertEquals(person.getCreditCardNumber(), "00000000000000");
- assertEquals(person.getCvv(), "007");
- }
-
- @Test
- public void testIndexOnEncryptedField() {
- persons.createIndex("cvv");
- EncryptedPerson person = persons.find(where("cvv").eq("008")).firstOrNull();
- assertNull(person);
- }
-}
diff --git a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/NitriteIdAsIdTest.java b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/NitriteIdAsIdTest.java
index 4b776ea17..a2f83265e 100644
--- a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/NitriteIdAsIdTest.java
+++ b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/NitriteIdAsIdTest.java
@@ -17,7 +17,7 @@
package org.dizitart.no2.integration.repository;
-import org.dizitart.no2.common.mapper.SimpleDocumentMapper;
+import org.dizitart.no2.common.mapper.SimpleNitriteMapper;
import org.dizitart.no2.integration.Retry;
import org.dizitart.no2.integration.repository.data.WithNitriteId;
import org.dizitart.no2.Nitrite;
@@ -54,7 +54,7 @@ public class NitriteIdAsIdTest {
@Before
public void before() {
db = TestUtil.createDb(fileName);
- SimpleDocumentMapper documentMapper = (SimpleDocumentMapper) db.getConfig().nitriteMapper();
+ SimpleNitriteMapper documentMapper = (SimpleNitriteMapper) db.getConfig().nitriteMapper();
documentMapper.registerEntityConverter(new WithNitriteId.WithNitriteIdConverter());
repo = db.getRepository(WithNitriteId.class);
@@ -78,7 +78,6 @@ public void testNitriteIdField() {
Cursor cursor = repo.find();
for (WithNitriteId withNitriteId : cursor) {
- System.out.println(withNitriteId.name);
assertNotNull(withNitriteId.idField);
}
diff --git a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/ObjectRepositoryNegativeTest.java b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/ObjectRepositoryNegativeTest.java
index 6d7135ef5..b26977b87 100644
--- a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/ObjectRepositoryNegativeTest.java
+++ b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/ObjectRepositoryNegativeTest.java
@@ -17,7 +17,7 @@
package org.dizitart.no2.integration.repository;
-import org.dizitart.no2.common.mapper.SimpleDocumentMapper;
+import org.dizitart.no2.common.mapper.SimpleNitriteMapper;
import org.dizitart.no2.integration.Retry;
import org.dizitart.no2.integration.repository.data.*;
import org.dizitart.no2.Nitrite;
@@ -51,7 +51,7 @@ public class ObjectRepositoryNegativeTest {
@Before
public void setUp() {
db = TestUtil.createDb(dbPath);
- SimpleDocumentMapper documentMapper = (SimpleDocumentMapper) db.getConfig().nitriteMapper();
+ SimpleNitriteMapper documentMapper = (SimpleNitriteMapper) db.getConfig().nitriteMapper();
documentMapper.registerEntityConverter(new WithPublicField.Converter());
documentMapper.registerEntityConverter(new WithObjectId.Converter());
documentMapper.registerEntityConverter(new WithOutId.Converter());
diff --git a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/ObjectRepositoryTest.java b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/ObjectRepositoryTest.java
index 360ee228d..c68b491f1 100644
--- a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/ObjectRepositoryTest.java
+++ b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/ObjectRepositoryTest.java
@@ -24,7 +24,7 @@
import org.dizitart.no2.collection.NitriteCollection;
import org.dizitart.no2.common.mapper.EntityConverter;
import org.dizitart.no2.common.meta.Attributes;
-import org.dizitart.no2.common.mapper.SimpleDocumentMapper;
+import org.dizitart.no2.common.mapper.SimpleNitriteMapper;
import org.dizitart.no2.common.mapper.NitriteMapper;
import org.dizitart.no2.exceptions.ValidationException;
import org.dizitart.no2.index.IndexType;
@@ -70,7 +70,7 @@ public class ObjectRepositoryTest {
@Before
public void setUp() {
- SimpleDocumentMapper mapper = new SimpleDocumentMapper();
+ SimpleNitriteMapper mapper = new SimpleNitriteMapper();
mapper.registerEntityConverter(new InternalClass.Converter());
mapper.registerEntityConverter(new EmployeeEntity.Converter());
mapper.registerEntityConverter(new StressRecord.Converter());
diff --git a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/RepositorySearchTest.java b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/RepositorySearchTest.java
index 066dd48af..b3437533e 100644
--- a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/RepositorySearchTest.java
+++ b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/RepositorySearchTest.java
@@ -23,7 +23,7 @@
import org.dizitart.no2.common.WriteResult;
import org.dizitart.no2.common.mapper.EntityConverter;
import org.dizitart.no2.common.mapper.NitriteMapper;
-import org.dizitart.no2.common.mapper.SimpleDocumentMapper;
+import org.dizitart.no2.common.mapper.SimpleNitriteMapper;
import org.dizitart.no2.exceptions.FilterException;
import org.dizitart.no2.exceptions.InvalidIdException;
import org.dizitart.no2.exceptions.NotIdentifiableException;
@@ -65,8 +65,8 @@ public void testEmployeeProjection() {
assertNotNull(employeeList);
assertNotNull(subEmployeeList);
- assertTrue(employeeList.size() > 0);
- assertTrue(subEmployeeList.size() > 0);
+ assertFalse(employeeList.isEmpty());
+ assertFalse(subEmployeeList.isEmpty());
assertEquals(employeeList.size(), subEmployeeList.size());
@@ -592,7 +592,7 @@ public TestData fromDocument(Document document, NitriteMapper nitriteMapper) {
}
}
- SimpleDocumentMapper documentMapper = (SimpleDocumentMapper) db.getConfig().nitriteMapper();
+ SimpleNitriteMapper documentMapper = (SimpleNitriteMapper) db.getConfig().nitriteMapper();
documentMapper.registerEntityConverter(new Converter());
TestData data1 = new TestData(new GregorianCalendar(2020, Calendar.JANUARY, 11).getTime());
diff --git a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/UnAnnotatedObjectTest.java b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/UnAnnotatedObjectTest.java
index cf793fb10..defd452ac 100644
--- a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/UnAnnotatedObjectTest.java
+++ b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/UnAnnotatedObjectTest.java
@@ -26,8 +26,7 @@
import static org.dizitart.no2.collection.FindOptions.orderBy;
import static org.dizitart.no2.filters.FluentFilter.where;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.*;
/**
* @author Anindya Chatterjee.
@@ -45,33 +44,25 @@ public void testFind() {
cursor = aObjectRepository.find(where("b.number").eq(160).not(),
orderBy("b.number", SortOrder.Ascending).skip(0).limit(10));
- System.out.println("Available - " + !cursor.isEmpty());
- System.out.println("Total Size - " + cursor.size());
-
Iterable findRecord = cursor.project(ClassA.class);
for (ClassA classA : findRecord) {
- System.out.println(classA);
+ assertNotNull(classA);
}
cursor = aObjectRepository.find(where("b.number").eq(160).not(),
orderBy("b.number", SortOrder.Descending).skip(2).limit(7));
- System.out.println("Available - " + !cursor.isEmpty());
- System.out.println("Total Size - " + cursor.size());
-
findRecord = cursor.project(ClassA.class);
for (ClassA classA : findRecord) {
- System.out.println(classA);
+ assertNotNull(classA);
}
cursor = cObjectRepository.find(where("id").gt(900),
orderBy("id", SortOrder.Descending).skip(2).limit(7));
- System.out.println("Available - " + !cursor.isEmpty());
- System.out.println("Total Size - " + cursor.size());
Iterable findRecordC = cursor.project(ClassC.class);
for (ClassC classC : findRecordC) {
- System.out.println(classC);
+ assertNotNull(classC);
}
}
}
diff --git a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/UniversalTextTokenizerTest.java b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/UniversalTextTokenizerTest.java
index d509adc70..c44e6ce63 100644
--- a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/UniversalTextTokenizerTest.java
+++ b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/repository/UniversalTextTokenizerTest.java
@@ -22,7 +22,7 @@
import org.dizitart.no2.collection.Document;
import org.dizitart.no2.common.mapper.EntityConverter;
import org.dizitart.no2.common.mapper.NitriteMapper;
-import org.dizitart.no2.common.mapper.SimpleDocumentMapper;
+import org.dizitart.no2.common.mapper.SimpleNitriteMapper;
import org.dizitart.no2.index.IndexType;
import org.dizitart.no2.index.NitriteTextIndexer;
import org.dizitart.no2.index.fulltext.Languages;
@@ -55,7 +55,7 @@ public class UniversalTextTokenizerTest extends BaseObjectRepositoryTest {
@Override
public void setUp() {
openDb();
- SimpleDocumentMapper documentMapper = (SimpleDocumentMapper) db.getConfig().nitriteMapper();
+ SimpleNitriteMapper documentMapper = (SimpleNitriteMapper) db.getConfig().nitriteMapper();
documentMapper.registerEntityConverter(new TextData.Converter());
textRepository = db.getRepository(TextData.class);
@@ -128,7 +128,6 @@ public void testUniversalFullTextIndexing() {
Cursor cursor = textRepository.find(where("text").text("Lorem"));
assertEquals(cursor.size(), 2);
for (TextData data : cursor) {
- System.out.println("Id for English text -> " + data.id);
if (data.id % 2 == 0 || data.id % 3 == 0 || data.id % 5 == 0) {
fail();
}
@@ -137,7 +136,6 @@ public void testUniversalFullTextIndexing() {
cursor = textRepository.find(where("text").text("শহর"));
assertEquals(cursor.size(), 5);
for (TextData data : cursor) {
- System.out.println("Id for Bengali text -> " + data.id);
if (data.id % 2 != 0) {
fail();
}
@@ -148,7 +146,6 @@ public void testUniversalFullTextIndexing() {
cursor = textRepository.find(where("text").text("*転閉*"));
assertEquals(cursor.size(), 2);
for (TextData data : cursor) {
- System.out.println("Id for Chinese text -> " + data.id);
if (data.id % 3 != 0) {
fail();
}
@@ -158,7 +155,6 @@ public void testUniversalFullTextIndexing() {
if (isProtected) {
assertEquals(cursor.size(), 1);
for (TextData data : cursor) {
- System.out.println("Id for Arabic text -> " + data.id);
if (data.id % 5 != 0) {
fail();
}
diff --git a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/transaction/TransactionCollectionTest.java b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/transaction/TransactionCollectionTest.java
index 6e3052aaa..b21bcf420 100644
--- a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/transaction/TransactionCollectionTest.java
+++ b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/transaction/TransactionCollectionTest.java
@@ -18,18 +18,21 @@
package org.dizitart.no2.integration.transaction;
import com.github.javafaker.Faker;
-import org.dizitart.no2.integration.collection.BaseCollectionTest;
+import lombok.extern.slf4j.Slf4j;
import org.dizitart.no2.collection.Document;
import org.dizitart.no2.collection.NitriteCollection;
import org.dizitart.no2.common.meta.Attributes;
-import org.dizitart.no2.exceptions.NitriteIOException;
import org.dizitart.no2.exceptions.TransactionException;
import org.dizitart.no2.index.IndexType;
+import org.dizitart.no2.integration.collection.BaseCollectionTest;
import org.dizitart.no2.transaction.Session;
import org.dizitart.no2.transaction.Transaction;
import org.junit.Test;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -44,6 +47,7 @@
/**
* @author Anindya Chatterjee
*/
+@Slf4j
public class TransactionCollectionTest extends BaseCollectionTest {
@Test
@@ -544,7 +548,7 @@ public void testConcurrentInsertAndRemove() {
transaction.commit();
} catch (Exception e) {
- e.printStackTrace();
+ log.error("Error in transaction", e);
transaction.rollback();
} finally {
transaction.close();
@@ -558,7 +562,7 @@ public void testConcurrentInsertAndRemove() {
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
- e.printStackTrace();
+ log.error("Error in transaction", e);
}
});
@@ -588,7 +592,7 @@ public void testConcurrentInsert() {
transaction.commit();
} catch (Exception e) {
- e.printStackTrace();
+ log.error("Error in transaction", e);
transaction.rollback();
} finally {
transaction.close();
@@ -602,7 +606,7 @@ public void testConcurrentInsert() {
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
- e.printStackTrace();
+ log.error("Error in transaction", e);
}
});
@@ -637,7 +641,7 @@ public void testConcurrentUpdate() {
transaction.commit();
} catch (Exception e) {
- e.printStackTrace();
+ log.error("Error in transaction", e);
transaction.rollback();
} finally {
transaction.close();
@@ -651,7 +655,7 @@ public void testConcurrentUpdate() {
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
- e.printStackTrace();
+ log.error("Error in transaction", e);
}
});
diff --git a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/transaction/TransactionRepositoryTest.java b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/transaction/TransactionRepositoryTest.java
index 4adab1075..7d3c1ff00 100644
--- a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/transaction/TransactionRepositoryTest.java
+++ b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/integration/transaction/TransactionRepositoryTest.java
@@ -18,6 +18,7 @@
package org.dizitart.no2.integration.transaction;
import com.github.javafaker.Faker;
+import lombok.extern.slf4j.Slf4j;
import org.dizitart.no2.collection.Document;
import org.dizitart.no2.collection.NitriteCollection;
import org.dizitart.no2.common.meta.Attributes;
@@ -45,6 +46,7 @@
/**
* @author Anindya Chatterjee
*/
+@Slf4j
public class TransactionRepositoryTest extends BaseObjectRepositoryTest {
@Test
@@ -588,7 +590,7 @@ public void testConcurrentInsertAndRemove() {
transaction.commit();
} catch (Exception e) {
- e.printStackTrace();
+ log.error("Error while inserting", e);
transaction.rollback();
} finally {
transaction.close();
@@ -602,7 +604,7 @@ public void testConcurrentInsertAndRemove() {
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
- e.printStackTrace();
+ log.error("Error while inserting", e);
}
});
@@ -632,7 +634,7 @@ public void testConcurrentInsert() {
transaction.commit();
} catch (Exception e) {
- e.printStackTrace();
+ log.error("Error while inserting", e);
transaction.rollback();
} finally {
transaction.close();
@@ -646,7 +648,7 @@ public void testConcurrentInsert() {
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
- e.printStackTrace();
+ log.error("Error while inserting", e);
}
});
@@ -679,7 +681,7 @@ public void testConcurrentUpdate() {
transaction.commit();
} catch (Exception e) {
- e.printStackTrace();
+ log.error("Error while updating", e);
transaction.rollback();
} finally {
transaction.close();
@@ -693,7 +695,7 @@ public void testConcurrentUpdate() {
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
- e.printStackTrace();
+ log.error("Error while updating", e);
}
});
diff --git a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/rocksdb/GithubIssues.java b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/rocksdb/GithubIssues.java
index f24145fd0..08b3c4d9f 100644
--- a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/rocksdb/GithubIssues.java
+++ b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/rocksdb/GithubIssues.java
@@ -22,7 +22,7 @@
import org.dizitart.no2.collection.Document;
import org.dizitart.no2.common.mapper.EntityConverter;
import org.dizitart.no2.common.mapper.NitriteMapper;
-import org.dizitart.no2.common.mapper.SimpleDocumentMapper;
+import org.dizitart.no2.common.mapper.SimpleNitriteMapper;
import org.dizitart.no2.repository.ObjectRepository;
import org.junit.Test;
@@ -42,14 +42,13 @@ public void testIssue412() {
.loadModule(dbModule)
.openOrCreate();
- SimpleDocumentMapper documentMapper = (SimpleDocumentMapper) db.getConfig().nitriteMapper();
+ SimpleNitriteMapper documentMapper = (SimpleNitriteMapper) db.getConfig().nitriteMapper();
documentMapper.registerEntityConverter(new TestData.Converter());
// Step 1
// NitriteCollection collection = db.getCollection("test");
// Document document = Document.createDocument("a", 1).put("b", 2);
// collection.insert(document);
-// System.out.println(collection.size());
// Step 2
ObjectRepository repository = db.getRepository(TestData.class);
@@ -57,7 +56,6 @@ public void testIssue412() {
testData.setId(1);
testData.setName("test");
repository.insert(testData);
- System.out.println(repository.size());
}
@Data
diff --git a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/rocksdb/RocksDBTest.java b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/rocksdb/RocksDBTest.java
index 454b048ee..6d97f4875 100644
--- a/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/rocksdb/RocksDBTest.java
+++ b/nitrite-rocksdb-adapter/src/test/java/org/dizitart/no2/rocksdb/RocksDBTest.java
@@ -22,13 +22,11 @@
import com.esotericsoftware.kryo.kryo5.io.Input;
import com.github.javafaker.Faker;
import lombok.Data;
+import lombok.extern.slf4j.Slf4j;
import org.dizitart.no2.Nitrite;
import org.dizitart.no2.integration.Retry;
import org.dizitart.no2.store.NitriteMap;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
+import org.junit.*;
import org.rocksdb.*;
import java.io.ByteArrayInputStream;
@@ -45,6 +43,7 @@
/**
* @author Anindya Chatterjee
*/
+@Slf4j
public class RocksDBTest {
private final String fileName = getRandomTempDbFile();
private Nitrite db;
@@ -105,24 +104,19 @@ public void testRocksDBMap() {
referenceMap.put(date3, 3L); // today + 5
referenceMap.put(date4, 4L); // today
- testLevelDBMap.entries().forEach(System.out::println);
- System.out.println("*****************");
- referenceMap.entrySet().forEach(System.out::println);
+ testLevelDBMap.entries().forEach(Assert::assertNotNull);
+ referenceMap.entrySet().forEach(Assert::assertNotNull);
cal = Calendar.getInstance();
cal.add(Calendar.DATE, 6);
Date date5 = cal.getTime();
- System.out.println("Floor Key " + referenceMap.floorKey(date5));
assertEquals(testLevelDBMap.floorKey(date5), referenceMap.floorKey(date5)); // x <= date5 : date3
- System.out.println("Lower Key " + referenceMap.lowerKey(date5));
assertEquals(testLevelDBMap.lowerKey(date5), referenceMap.lowerKey(date5)); // x < date5 : date4
- System.out.println("Higher Key " + referenceMap.higherKey(date5));
assertEquals(testLevelDBMap.higherKey(date5), referenceMap.higherKey(date5)); // date5 >= x :
- System.out.println("Ceiling Key " + referenceMap.ceilingKey(date5));
assertEquals(testLevelDBMap.ceilingKey(date5), referenceMap.ceilingKey(date5));
}
@@ -141,18 +135,14 @@ public void testRocksDBMapInteger() {
referenceMap.put(3, 3); // today + 5
referenceMap.put(4, 4); // today
- testLevelDBMap.entries().forEach(System.out::println);
+ testLevelDBMap.entries().forEach(Assert::assertNotNull);
- System.out.println("Floor Key " + referenceMap.floorKey(3));
assertEquals(testLevelDBMap.floorKey(3), referenceMap.floorKey(3)); // x <= date5 : date3
- System.out.println("Lower Key " + referenceMap.lowerKey(3));
assertEquals(testLevelDBMap.lowerKey(3), referenceMap.lowerKey(3)); // x < date5 : date4
- System.out.println("Higher Key " + referenceMap.higherKey(3));
assertEquals(testLevelDBMap.higherKey(3), referenceMap.higherKey(3)); // date5 >= x :
- System.out.println("Ceiling Key " + referenceMap.ceilingKey(3));
assertEquals(testLevelDBMap.ceilingKey(3), referenceMap.ceilingKey(3));
}
@@ -167,25 +157,13 @@ public void testNaturalSort() {
map.put("A", 12);
map.put("1", 11);
- map.entries().forEach(System.out::println);
+ map.entries().forEach(Assert::assertNotNull);
treeMap.put("z", 10);
treeMap.put("Z", 14);
treeMap.put("w", 13);
treeMap.put("A", 12);
treeMap.put("1", 11);
-
- System.out.println(map.floorKey("w"));
- System.out.println(map.higherKey("w"));
- System.out.println(map.ceilingKey("w"));
- System.out.println(map.lowerKey("w"));
-
- System.out.println("***************");
-
- System.out.println(treeMap.floorKey("w"));
- System.out.println(treeMap.higherKey("w"));
- System.out.println(treeMap.ceilingKey("w"));
- System.out.println(treeMap.lowerKey("w"));
}
@Test
@@ -275,7 +253,6 @@ public void testPrev() {
byte[] key = iterator.key();
byte[] value = iterator.value();
- System.out.println("Key: Value = " + new String(key) + ": " + new String(value));
iterator.prev();
}
}
@@ -290,7 +267,7 @@ public void testPrev() {
}
} // frees the db and the db options
} catch (RocksDBException e) {
- e.printStackTrace();
+ log.error("Error while opening rocksdb", e);
}
} // frees the column family options
}
@@ -306,7 +283,6 @@ public void testPrevNitriteMap() {
Long floorKey = testLevelDBMap.floorKey(10L);
while (floorKey != null) {
- System.out.println("Key: Value = " + floorKey + ": " + testLevelDBMap.get(floorKey));
floorKey = testLevelDBMap.lowerKey(floorKey);
}
}
diff --git a/nitrite-spatial/pom.xml b/nitrite-spatial/pom.xml
index d269889f7..f2cbe47fc 100644
--- a/nitrite-spatial/pom.xml
+++ b/nitrite-spatial/pom.xml
@@ -85,6 +85,14 @@
org.apache.maven.plugins
maven-javadoc-plugin
+
+
+ org.dizitart.no2.spatial.mapper,
+
+
+ **/*GeometryUtils.java
+
+
org.apache.maven.plugins
diff --git a/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/FluentFilter.java b/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/FluentFilter.java
index bf6a2bf11..5d5833ff7 100644
--- a/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/FluentFilter.java
+++ b/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/FluentFilter.java
@@ -21,11 +21,12 @@
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.Point;
+
/**
- * Fluent filter api for spatial data
- *
+ * A fluent filter api for spatial queries.
+ *
+ * @since 4.0
* @author Anindya Chatterjee
- * @since 4.0.0
*/
public class FluentFilter {
private String field;
@@ -34,10 +35,10 @@ private FluentFilter() {
}
/**
- * Where clause for fluent filter.
+ * Creates a new {@link FluentFilter} instance with the specified field.
*
- * @param field the field
- * @return the fluent filter
+ * @param field the field to filter on
+ * @return the new {@link FluentFilter} instance
*/
public static FluentFilter where(String field) {
FluentFilter filter = new FluentFilter();
@@ -49,8 +50,8 @@ public static FluentFilter where(String field) {
* Creates a spatial filter which matches documents where the spatial data
* of a field intersects the specified {@link Geometry} value.
*
- * @param geometry the geometry
- * @return the filter
+ * @param geometry the geometry to intersect with
+ * @return the new {@link Filter} instance
*/
public Filter intersects(Geometry geometry) {
return new IntersectsFilter(field, geometry);
@@ -60,8 +61,8 @@ public Filter intersects(Geometry geometry) {
* Creates a spatial filter which matches documents where the spatial data
* of a field is within the specified {@link Geometry} value.
*
- * @param geometry the geometry
- * @return the filter
+ * @param geometry the geometry to check for containment within
+ * @return the new {@link Filter} instance
*/
public Filter within(Geometry geometry) {
return new WithinFilter(field, geometry);
@@ -71,9 +72,9 @@ public Filter within(Geometry geometry) {
* Creates a spatial filter which matches documents where the spatial data
* of a field is near the specified coordinate.
*
- * @param point the point
- * @param distance the distance
- * @return the filter
+ * @param point the coordinate to check proximity to
+ * @param distance the maximum distance to consider
+ * @return the new {@link Filter} instance
*/
public Filter near(Coordinate point, Double distance) {
return new NearFilter(field, point, distance);
@@ -83,9 +84,9 @@ public Filter near(Coordinate point, Double distance) {
* Creates a spatial filter which matches documents where the spatial data
* of a field is near the specified point.
*
- * @param point the point
- * @param distance the distance
- * @return the filter
+ * @param point the point to check proximity to
+ * @param distance the maximum distance to consider
+ * @return the new {@link Filter} instance
*/
public Filter near(Point point, Double distance) {
return new NearFilter(field, point, distance);
diff --git a/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/GeometryUtils.java b/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/GeometryUtils.java
index 0ec577d71..f414ca8c7 100644
--- a/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/GeometryUtils.java
+++ b/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/GeometryUtils.java
@@ -23,6 +23,10 @@
import org.locationtech.jts.io.WKTReader;
import org.locationtech.jts.io.WKTWriter;
+/**
+ * @since 4.0
+ * @author Anindya Chatterjee
+ */
public class GeometryUtils {
private static final String GEOMETRY_ID = "geometry:";
private static WKTWriter writer;
diff --git a/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/NitriteBoundingBox.java b/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/NitriteBoundingBox.java
index f8249b568..77acc4a52 100644
--- a/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/NitriteBoundingBox.java
+++ b/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/NitriteBoundingBox.java
@@ -26,7 +26,6 @@
import java.io.ObjectOutputStream;
/**
- *
* @since 4.0
* @author Anindya Chatterjee
*/
diff --git a/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/SpatialFilter.java b/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/SpatialFilter.java
index d42853e52..c437f36c0 100644
--- a/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/SpatialFilter.java
+++ b/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/SpatialFilter.java
@@ -23,9 +23,14 @@
import org.locationtech.jts.geom.Geometry;
/**
- * Represents a spatial filter.
- *
- * @since 4.0.0
+ * The abstract base class for all spatial filters in Nitrite.
+ *
+ * A spatial filter is used to query Nitrite database for documents that have a specific spatial relationship
+ * with a given geometry. It extends {@link IndexOnlyFilter} and provides an implementation for the
+ * {@link #supportedIndexType()} method.
+ *
+ *
+ * @since 4.0
* @author Anindya Chatterjee
*/
public abstract class SpatialFilter extends IndexOnlyFilter {
@@ -42,6 +47,11 @@ protected SpatialFilter(String field, Geometry geometry) {
this.geometry = geometry;
}
+ /**
+ * Returns the geometry value of this filter.
+ *
+ * @return the geometry value of this filter.
+ */
@Override
public Geometry getValue() {
return geometry;
diff --git a/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/SpatialIndex.java b/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/SpatialIndex.java
index 303155ae8..eec76b6f9 100644
--- a/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/SpatialIndex.java
+++ b/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/SpatialIndex.java
@@ -43,7 +43,7 @@
/**
* Represents a spatial index in nitrite.
*
- * @since 4.0.0
+ * @since 4.0
* @author Anindya Chatterjee
*/
public class SpatialIndex implements NitriteIndex {
diff --git a/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/SpatialIndexer.java b/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/SpatialIndexer.java
index f39c50a1f..9f45b440c 100644
--- a/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/SpatialIndexer.java
+++ b/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/SpatialIndexer.java
@@ -30,14 +30,18 @@
import java.util.concurrent.ConcurrentHashMap;
/**
- * Represents a spatial data indexer.
- *
+ * The {@code SpatialIndexer} class implements the {@link NitriteIndexer}
+ * interface and provides support for creating and managing spatial
+ * indexes in Nitrite database. It uses the {@link SpatialIndex} class to create
+ * and manage the indexes.
+ *
+ * @since 4.0
* @author Anindya Chatterjee
- * @since 4.0.0
*/
public class SpatialIndexer implements NitriteIndexer {
/**
- * Spatial index type.
+ * The name of the spatial index type. To be used while creating a spatial
+ * index.
*/
public static final String SPATIAL_INDEX = "Spatial";
private final Map indexRegistry;
@@ -74,7 +78,8 @@ public void writeIndexEntry(FieldValues fieldValues, IndexDescriptor indexDescri
}
@Override
- public void removeIndexEntry(FieldValues fieldValues, IndexDescriptor indexDescriptor, NitriteConfig nitriteConfig) {
+ public void removeIndexEntry(FieldValues fieldValues, IndexDescriptor indexDescriptor,
+ NitriteConfig nitriteConfig) {
SpatialIndex spatialIndex = findSpatialIndex(indexDescriptor, nitriteConfig);
spatialIndex.remove(fieldValues);
}
diff --git a/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/SpatialModule.java b/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/SpatialModule.java
index aa07b5f33..f91f3c185 100644
--- a/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/SpatialModule.java
+++ b/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/SpatialModule.java
@@ -23,15 +23,23 @@
import static org.dizitart.no2.common.util.Iterables.setOf;
+
/**
- * A nitrite module to enable spatial data indexing.
- *
- * @since 4.0.0
+ * A Nitrite module for spatial indexing. This module provides a
+ * {@link SpatialIndexer} plugin for Nitrite database.
+ *
+ * @since 4.0
* @author Anindya Chatterjee
*/
public class SpatialModule implements NitriteModule {
private SpatialIndexer spatialIndexer;
+ /**
+ * {@inheritDoc}
+ * Returns a set of Nitrite plugins, which includes the SpatialIndexer.
+ *
+ * @return a set of Nitrite plugins, which includes the SpatialIndexer.
+ */
@Override
public Set plugins() {
if (spatialIndexer == null) {
diff --git a/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/mapper/GeometryDeserializer.java b/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/mapper/GeometryDeserializer.java
index e9288f867..105b9791b 100644
--- a/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/mapper/GeometryDeserializer.java
+++ b/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/mapper/GeometryDeserializer.java
@@ -19,16 +19,15 @@
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer;
-import lombok.extern.slf4j.Slf4j;
import org.dizitart.no2.spatial.GeometryUtils;
import org.locationtech.jts.geom.Geometry;
import java.io.IOException;
/**
+ * @since 4.0
* @author Anindya Chatterjee
*/
-@Slf4j
class GeometryDeserializer extends StdScalarDeserializer {
protected GeometryDeserializer() {
diff --git a/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/mapper/GeometryModule.java b/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/mapper/GeometryModule.java
index 74ffac9be..c6870681f 100644
--- a/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/mapper/GeometryModule.java
+++ b/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/mapper/GeometryModule.java
@@ -20,10 +20,8 @@
import org.locationtech.jts.geom.Geometry;
/**
- * Class that registers capability of serializing {@link Geometry} objects with the Jackson core.
- *
* @author Anindya Chatterjee
- * @since 4.0.0
+ * @since 4.0
*/
public class GeometryModule extends SimpleModule {
diff --git a/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/mapper/GeometrySerializer.java b/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/mapper/GeometrySerializer.java
index dbb9c7b44..a959d6047 100644
--- a/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/mapper/GeometrySerializer.java
+++ b/nitrite-spatial/src/main/java/org/dizitart/no2/spatial/mapper/GeometrySerializer.java
@@ -25,6 +25,7 @@
import java.io.IOException;
/**
+ * @since 4.0
* @author Anindya Chatterjee
*/
class GeometrySerializer extends StdScalarSerializer {
diff --git a/nitrite-spatial/src/test/java/org/dizitart/no2/spatial/Retry.java b/nitrite-spatial/src/test/java/org/dizitart/no2/spatial/Retry.java
index 97691f917..d6df10c41 100644
--- a/nitrite-spatial/src/test/java/org/dizitart/no2/spatial/Retry.java
+++ b/nitrite-spatial/src/test/java/org/dizitart/no2/spatial/Retry.java
@@ -1,5 +1,6 @@
package org.dizitart.no2.spatial;
+import lombok.extern.slf4j.Slf4j;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
@@ -7,6 +8,7 @@
/**
* @author Anindya Chatterjee
*/
+@Slf4j
public class Retry implements TestRule {
private final int retryCount;
@@ -31,11 +33,13 @@ public void evaluate() throws Throwable {
return;
} catch (Throwable t) {
caughtThrowable = t;
- System.err.println(description.getDisplayName() + ": run " + (i + 1) + " failed");
+ log.warn(description.getDisplayName() + ": run " + (i + 1) + " failed");
}
}
- System.err.println(description.getDisplayName() + ": giving up after " + retryCount + " failures");
- throw caughtThrowable;
+ log.error(description.getDisplayName() + ": giving up after " + retryCount + " failures");
+ if (caughtThrowable != null) {
+ throw caughtThrowable;
+ }
}
};
}
diff --git a/nitrite-spatial/src/test/java/org/dizitart/no2/spatial/SpatialViewer.java b/nitrite-spatial/src/test/java/org/dizitart/no2/spatial/SpatialViewer.java
index 0893b2180..cf3946800 100644
--- a/nitrite-spatial/src/test/java/org/dizitart/no2/spatial/SpatialViewer.java
+++ b/nitrite-spatial/src/test/java/org/dizitart/no2/spatial/SpatialViewer.java
@@ -17,6 +17,7 @@
package org.dizitart.no2.spatial;
+import lombok.extern.slf4j.Slf4j;
import org.locationtech.jts.awt.ShapeWriter;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.io.WKTReader;
@@ -27,6 +28,7 @@
/**
* @author Anindya Chatterjee
*/
+@Slf4j(topic = "nitrite-spatial")
public class SpatialViewer {
public static void main(String[] args) {
JFrame f = new JFrame();
@@ -76,7 +78,7 @@ public void paint(Graphics g) {
g2d.draw(searchShape);
} catch (Exception e) {
- e.printStackTrace();
+ log.error("Error while drawing", e);
}
}
}
diff --git a/nitrite-spatial/src/test/java/org/dizitart/no2/spatial/TestUtil.java b/nitrite-spatial/src/test/java/org/dizitart/no2/spatial/TestUtil.java
index b131e2f47..aecad83ef 100644
--- a/nitrite-spatial/src/test/java/org/dizitart/no2/spatial/TestUtil.java
+++ b/nitrite-spatial/src/test/java/org/dizitart/no2/spatial/TestUtil.java
@@ -17,7 +17,7 @@
package org.dizitart.no2.spatial;
-import lombok.SneakyThrows;
+import lombok.extern.slf4j.Slf4j;
import org.dizitart.no2.Nitrite;
import org.dizitart.no2.common.mapper.JacksonMapperModule;
import org.dizitart.no2.mvstore.MVStoreModule;
@@ -33,6 +33,7 @@
/**
* @author Anindya Chatterjee
*/
+@Slf4j
public class TestUtil {
public static String getRandomTempDbFile() {
String dataDir = System.getProperty("java.io.tmpdir") + File.separator + "nitrite" + File.separator + "data";
@@ -56,8 +57,11 @@ public static Nitrite createDb(String fileName) {
.openOrCreate();
}
- @SneakyThrows
public static void deleteDb(String fileName) {
- Files.delete(Paths.get(fileName));
+ try {
+ Files.delete(Paths.get(fileName));
+ } catch (Exception e) {
+ log.error("Error while deleting db", e);
+ }
}
}
diff --git a/nitrite-support/README.md b/nitrite-support/README.md
index f56155013..ba9cb29ee 100644
--- a/nitrite-support/README.md
+++ b/nitrite-support/README.md
@@ -31,7 +31,22 @@ implementation 'org.dizitart:nitrite-support'
```java
// export data to a json file
-Exporter exporter = Exporter.of(sourceDb);
+ExportOptions exportOptions = new ExportOptions();
+exportOptions.setNitriteFactory(() {
+ MVStoreModule storeModule = MVStoreModule.withConfig()
+ .filePath('/tmp/test-old.db')
+ .build();
+
+ return Nitrite.builder()
+ .compressed()
+ .loadModule(storeModule)
+ .openOrCreate();
+});
+exportOptions.setCollections(List.of("first"));
+exportOptions.setRepositories(List.of("org.dizitart.no2.support.data.Employee"));
+exportOptions.setKeyedRepositories(Map.of("key", Set.of("org.dizitart.no2.support.data.Employee")));
+
+Exporter exporter = Exporter.withOptions(exportOptions);
exporter.exportTo(schemaFile);
```
@@ -39,6 +54,18 @@ exporter.exportTo(schemaFile);
```java
// import data from a json file
-Importer importer = Importer.of(destDb);
+ImportOptions importOptions = new ImportOptions();
+importOptions.setNitriteFactory(() {
+ MVStoreModule storeModule = MVStoreModule.withConfig()
+ .filePath('/tmp/test-old.db')
+ .build();
+
+ return Nitrite.builder()
+ .compressed()
+ .loadModule(storeModule)
+ .openOrCreate();
+});
+
+Importer importer = Importer.withOptions(importOptions);
importer.importFrom(schemaFile);
```
diff --git a/nitrite-support/pom.xml b/nitrite-support/pom.xml
index d29eda104..13257affc 100644
--- a/nitrite-support/pom.xml
+++ b/nitrite-support/pom.xml
@@ -42,10 +42,6 @@
com.fasterxml.jackson.core
jackson-databind
-
- commons-codec
- commons-codec
-
org.projectlombok
lombok
@@ -95,6 +91,11 @@
org.apache.maven.plugins
maven-javadoc-plugin
+
+
+ **/*Exporter.java
+
+
org.apache.maven.plugins
diff --git a/nitrite-support/src/main/java/org/dizitart/no2/support/ExportOptions.java b/nitrite-support/src/main/java/org/dizitart/no2/support/ExportOptions.java
deleted file mode 100644
index 8ec537883..000000000
--- a/nitrite-support/src/main/java/org/dizitart/no2/support/ExportOptions.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (c) 2017-2020. Nitrite author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.dizitart.no2.support;
-
-import lombok.Getter;
-import lombok.Setter;
-import org.dizitart.no2.common.PersistentCollection;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Represents export options.
- *
- * @author Anindya Chatterjee
- * @see Exporter
- * @since 1.0
- */
-@Getter
-@Setter
-public class ExportOptions {
-
- /**
- * Indicates if the export operation exports indices information.
- *
- * [icon="{@docRoot}/note.png"]
- * NOTE: Default value is `true`.
- *
- * @param exportIndices a value indicating if indices information will be exported.
- * @return `true` if indices information is exported; otherwise, `false`.
- */
- private boolean exportIndices = true;
-
- /**
- * Indicates if the export operation exports collection data.
- *
- * [icon="{@docRoot}/note.png"]
- * NOTE: Default value is `true`.
- *
- * @param exportData a value indicating if collection data will be exported.
- * @return `true` if collection data is exported; otherwise, `false`.
- */
- private boolean exportData = true;
-
- /**
- * Specifies a list of {@link PersistentCollection}s to be exported.
- *
- * [icon="{@docRoot}/note.png"]
- * NOTE: If empty, all collections will be exported.
- *
- * @param collections list of all collections to be exported.
- * @return list of collections.
- */
- private List> collections = new ArrayList<>();
-}
diff --git a/nitrite-support/src/main/java/org/dizitart/no2/support/NitriteJsonExporter.java b/nitrite-support/src/main/java/org/dizitart/no2/support/NitriteJsonExporter.java
deleted file mode 100644
index 2ed1ff5f7..000000000
--- a/nitrite-support/src/main/java/org/dizitart/no2/support/NitriteJsonExporter.java
+++ /dev/null
@@ -1,226 +0,0 @@
-/*
- * Copyright (c) 2017-2020. Nitrite author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.dizitart.no2.support;
-
-import com.fasterxml.jackson.core.JsonGenerator;
-import org.apache.commons.codec.binary.Hex;
-import org.dizitart.no2.Nitrite;
-import org.dizitart.no2.collection.Document;
-import org.dizitart.no2.collection.DocumentCursor;
-import org.dizitart.no2.collection.NitriteCollection;
-import org.dizitart.no2.common.PersistentCollection;
-import org.dizitart.no2.exceptions.NitriteIOException;
-import org.dizitart.no2.index.IndexDescriptor;
-import org.dizitart.no2.repository.ObjectRepository;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.ObjectOutputStream;
-import java.util.*;
-
-import static org.dizitart.no2.common.Constants.*;
-import static org.dizitart.no2.common.util.ObjectUtils.getKeyName;
-import static org.dizitart.no2.common.util.ObjectUtils.getKeyedRepositoryType;
-
-/**
- * @author Anindya Chatterjee
- */
-class NitriteJsonExporter {
- private final Nitrite db;
- private JsonGenerator generator;
- private ExportOptions options;
-
- public NitriteJsonExporter(Nitrite db) {
- this.db = db;
- }
-
- public void setGenerator(JsonGenerator generator) {
- this.generator = generator;
- }
-
- public void exportData() throws IOException, ClassNotFoundException {
- List> collections = options.getCollections();
- Set collectionNames;
- Set repositoryNames;
- Map> keyedRepositoryNames;
- if (collections.isEmpty()) {
- collectionNames = db.listCollectionNames();
- repositoryNames = db.listRepositories();
- keyedRepositoryNames = db.listKeyedRepositories();
- } else {
- collectionNames = new HashSet<>();
- repositoryNames = new HashSet<>();
- keyedRepositoryNames = new HashMap<>();
- for (PersistentCollection> collection : collections) {
- String name;
- if (collection instanceof NitriteCollection) {
- NitriteCollection nitriteCollection = (NitriteCollection) collection;
- name = nitriteCollection.getName();
- collectionNames.add(name);
- } else if (collection instanceof ObjectRepository) {
- ObjectRepository> repository = (ObjectRepository>) collection;
- name = repository.getDocumentCollection().getName();
- if (name.contains(KEY_OBJ_SEPARATOR)) {
- String key = getKeyName(name);
- String type = getKeyedRepositoryType(name);
- Set types;
- if (keyedRepositoryNames.containsKey(key)) {
- types = keyedRepositoryNames.get(key);
- } else {
- types = new LinkedHashSet<>();
- }
- types.add(type);
- keyedRepositoryNames.put(key, types);
- } else {
- repositoryNames.add(name);
- }
- }
- }
- }
- exportData(collectionNames, repositoryNames, keyedRepositoryNames);
- generator.close();
- }
-
- private void exportData(Set collectionNames,
- Set repositoryNames,
- Map> keyedRepositoryNames) throws IOException, ClassNotFoundException {
- generator.writeStartObject();
-
- generator.writeFieldName(TAG_COLLECTIONS);
- generator.writeStartArray();
- for (String collectionName : collectionNames) {
- NitriteCollection nitriteCollection = db.getCollection(collectionName);
- writeCollection(nitriteCollection);
- }
- generator.writeEndArray();
-
- generator.writeFieldName(TAG_REPOSITORIES);
- generator.writeStartArray();
- for (String repoName : repositoryNames) {
- Class> type = Class.forName(repoName);
- ObjectRepository> repository = db.getRepository(type);
- writeRepository(repository);
- }
- generator.writeEndArray();
-
- generator.writeFieldName(TAG_KEYED_REPOSITORIES);
- generator.writeStartArray();
- for (Map.Entry> entry : keyedRepositoryNames.entrySet()) {
- String key = entry.getKey();
- Set typeNames = entry.getValue();
- for (String typeName : typeNames) {
- Class> type = Class.forName(typeName);
- ObjectRepository> repository = db.getRepository(type, key);
- writeKeyedRepository(key, repository);
- }
- }
- generator.writeEndArray();
-
- generator.writeEndObject();
- }
-
-
- private void writeRepository(ObjectRepository> repository) throws IOException {
- generator.writeStartObject();
- generator.writeFieldName(TAG_TYPE);
- generator.writeString(repository.getType().getName());
-
- Collection indices = repository.listIndices();
- writeIndices(indices);
-
- DocumentCursor cursor = repository.getDocumentCollection().find();
- writeContent(cursor);
- generator.writeEndObject();
- }
-
- private void writeKeyedRepository(String key, ObjectRepository> repository) throws IOException {
- generator.writeStartObject();
-
- generator.writeFieldName(TAG_KEY);
- generator.writeString(key);
-
- generator.writeFieldName(TAG_TYPE);
- generator.writeString(repository.getType().getName());
-
- Collection indices = repository.listIndices();
- writeIndices(indices);
-
- DocumentCursor cursor = repository.getDocumentCollection().find();
- writeContent(cursor);
- generator.writeEndObject();
- }
-
- private void writeCollection(NitriteCollection nitriteCollection) throws IOException {
- generator.writeStartObject();
- generator.writeFieldName(TAG_NAME);
- generator.writeString(nitriteCollection.getName());
-
- Collection indices = nitriteCollection.listIndices();
- writeIndices(indices);
-
- DocumentCursor cursor = nitriteCollection.find();
- writeContent(cursor);
- generator.writeEndObject();
- }
-
- private void writeIndices(Collection indices) throws IOException {
- generator.writeFieldName(TAG_INDICES);
- generator.writeStartArray();
- if (options.isExportIndices()) {
- for (IndexDescriptor index : indices) {
- generator.writeStartObject();
- generator.writeFieldName(TAG_INDEX);
- generator.writeObject(writeEncodedObject(index));
- generator.writeEndObject();
- }
- }
- generator.writeEndArray();
- }
-
- private void writeContent(DocumentCursor cursor) throws IOException {
- generator.writeFieldName(TAG_DATA);
- generator.writeStartArray();
- if (options.isExportData()) {
- for (Document document : cursor) {
- generator.writeStartObject();
- generator.writeFieldName(TAG_KEY);
- generator.writeObject(writeEncodedObject(document.get(DOC_ID)));
-
- generator.writeFieldName(TAG_VALUE);
- generator.writeObject(writeEncodedObject(document));
- generator.writeEndObject();
- }
- }
- generator.writeEndArray();
- }
-
- public void setOptions(ExportOptions options) {
- this.options = options;
- }
-
- private String writeEncodedObject(Object object) {
- try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
- try (ObjectOutputStream oos = new ObjectOutputStream(os)) {
- oos.writeObject(object);
- byte[] data = os.toByteArray();
- return Hex.encodeHexString(data);
- }
- } catch (IOException e) {
- throw new NitriteIOException("Failed to write object", e);
- }
- }
-}
diff --git a/nitrite-support/src/main/java/org/dizitart/no2/support/NitriteJsonImporter.java b/nitrite-support/src/main/java/org/dizitart/no2/support/NitriteJsonImporter.java
deleted file mode 100644
index 059b21c5c..000000000
--- a/nitrite-support/src/main/java/org/dizitart/no2/support/NitriteJsonImporter.java
+++ /dev/null
@@ -1,233 +0,0 @@
-/*
- * Copyright (c) 2017-2020. Nitrite author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.dizitart.no2.support;
-
-import com.fasterxml.jackson.core.JsonParser;
-import com.fasterxml.jackson.core.JsonToken;
-import org.apache.commons.codec.binary.Hex;
-import org.dizitart.no2.Nitrite;
-import org.dizitart.no2.collection.Document;
-import org.dizitart.no2.collection.NitriteCollection;
-import org.dizitart.no2.common.PersistentCollection;
-import org.dizitart.no2.exceptions.NitriteIOException;
-import org.dizitart.no2.index.IndexDescriptor;
-import org.dizitart.no2.repository.ObjectRepository;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.ObjectInputStream;
-
-import static org.dizitart.no2.common.Constants.*;
-import static org.dizitart.no2.index.IndexOptions.indexOptions;
-
-/**
- * @author Anindya Chatterjee.
- */
-class NitriteJsonImporter {
- private JsonParser parser;
- private final Nitrite db;
-
- public NitriteJsonImporter(Nitrite db) {
- this.db = db;
- }
-
- public void setParser(JsonParser parser) {
- this.parser = parser;
- }
-
- public void importData() throws IOException, ClassNotFoundException {
- while (parser.nextToken() != JsonToken.END_OBJECT) {
- String fieldName = parser.getCurrentName();
-
- if (TAG_COLLECTIONS.equals(fieldName)) {
- readCollection();
- }
-
- if (TAG_REPOSITORIES.equals(fieldName)) {
- readRepository();
- }
-
- if (TAG_KEYED_REPOSITORIES.equals(fieldName)) {
- readKeyedRepository();
- }
- }
- }
-
- private void readRepository() throws IOException, ClassNotFoundException {
- ObjectRepository> repository = null;
- // move to [
- parser.nextToken();
-
- // loop till token equal to "]"
- while (parser.nextToken() != JsonToken.END_ARRAY) {
- // loop until end of collection object
- while (parser.nextToken() != JsonToken.END_OBJECT) {
- String fieldName = parser.getCurrentName();
-
- if (TAG_TYPE.equals(fieldName)) {
- // move to next token
- parser.nextToken();
-
- String typeId = parser.getText();
- Class> type = Class.forName(typeId);
- repository = db.getRepository(type);
- }
-
- if (TAG_INDICES.equals(fieldName)) {
- readIndices(repository);
- }
-
- if (TAG_DATA.equals(fieldName) && repository != null) {
- readCollectionData(repository.getDocumentCollection());
- }
- }
- }
- }
-
- private void readKeyedRepository() throws IOException, ClassNotFoundException {
- ObjectRepository> repository = null;
- // move to [
- parser.nextToken();
-
- // loop till token equal to "]"
- while (parser.nextToken() != JsonToken.END_ARRAY) {
- String key = null;
-
- // loop until end of collection object
- while (parser.nextToken() != JsonToken.END_OBJECT) {
- String fieldName = parser.getCurrentName();
-
- if (TAG_KEY.equals(fieldName)) {
- parser.nextToken();
- key = parser.getText();
- }
-
- if (key != null && TAG_TYPE.equals(fieldName)) {
- // move to next token
- parser.nextToken();
-
- String typeId = parser.getText();
- Class> type = Class.forName(typeId);
- repository = db.getRepository(type, key);
- }
-
- if (TAG_INDICES.equals(fieldName)) {
- readIndices(repository);
- }
-
- if (TAG_DATA.equals(fieldName) && repository != null) {
- readCollectionData(repository.getDocumentCollection());
- }
- }
- }
- }
-
- private void readCollection() throws IOException {
- NitriteCollection collection = null;
- // move to [
- parser.nextToken();
-
- // loop till token equal to "]"
- while (parser.nextToken() != JsonToken.END_ARRAY) {
- // loop until end of collection object
- while (parser.nextToken() != JsonToken.END_OBJECT) {
- String fieldName = parser.getCurrentName();
-
- if (TAG_NAME.equals(fieldName)) {
- // move to next token
- parser.nextToken();
-
- String collectionName = parser.getText();
- collection = db.getCollection(collectionName);
- }
-
- if (TAG_INDICES.equals(fieldName)) {
- readIndices(collection);
- }
-
- if (TAG_DATA.equals(fieldName)) {
- readCollectionData(collection);
- }
- }
- }
- }
-
- private void readIndices(PersistentCollection> collection) throws IOException {
- // move to [
- parser.nextToken();
-
- // loop till token equal to "]"
- while (parser.nextToken() != JsonToken.END_ARRAY) {
- // loop until end of collection object
- while (parser.nextToken() != JsonToken.END_OBJECT) {
- String fieldName = parser.getCurrentName();
-
- if (TAG_INDEX.equals(fieldName)) {
- parser.nextToken();
- String data = parser.readValueAs(String.class);
- IndexDescriptor index = (IndexDescriptor) readEncodedObject(data);
- if (index != null) {
- String[] fieldNames = index.getFields().getFieldNames().toArray(new String[0]);
- if (collection != null && index.getFields() != null && !collection.hasIndex(fieldNames)) {
- collection.createIndex(indexOptions(index.getIndexType()), fieldNames);
- }
- }
- }
- }
- }
- }
-
- private void readCollectionData(NitriteCollection collection) throws IOException {
- // move to [
- parser.nextToken();
-
- // loop till token equal to "]"
- while (parser.nextToken() != JsonToken.END_ARRAY) {
- // loop until end of collection object
- while (parser.nextToken() != JsonToken.END_OBJECT) {
- String fieldName = parser.getCurrentName();
-
- if (TAG_KEY.equals(fieldName)) {
- parser.nextToken();
- parser.readValueAs(String.class);
- }
-
- if (TAG_VALUE.equals(fieldName)) {
- parser.nextToken();
- String data = parser.readValueAs(String.class);
- Document document = (Document) readEncodedObject(data);
- if (collection != null) {
- collection.insert(document);
- }
- }
- }
- }
- }
-
- private Object readEncodedObject(String hexString) {
- try {
- byte[] data = Hex.decodeHex(hexString);
- try (ByteArrayInputStream is = new ByteArrayInputStream(data)) {
- try (ObjectInputStream ois = new ObjectInputStream(is)) {
- return ois.readObject();
- }
- }
- } catch (Exception e) {
- throw new NitriteIOException("Error while reading data", e);
- }
- }
-}
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/crypto/AESEncryptor.java b/nitrite-support/src/main/java/org/dizitart/no2/support/crypto/AESEncryptor.java
similarity index 79%
rename from nitrite/src/main/java/org/dizitart/no2/common/crypto/AESEncryptor.java
rename to nitrite-support/src/main/java/org/dizitart/no2/support/crypto/AESEncryptor.java
index f3ec0efdd..81e575e37 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/crypto/AESEncryptor.java
+++ b/nitrite-support/src/main/java/org/dizitart/no2/support/crypto/AESEncryptor.java
@@ -15,9 +15,9 @@
*
*/
-package org.dizitart.no2.common.crypto;
+package org.dizitart.no2.support.crypto;
-import org.dizitart.no2.common.util.Base64;
+import org.apache.commons.codec.binary.Base64;
import org.dizitart.no2.common.util.CryptoUtils;
import org.dizitart.no2.common.util.SecureString;
import org.dizitart.no2.exceptions.NitriteSecurityException;
@@ -30,12 +30,19 @@
import java.nio.charset.StandardCharsets;
/**
- * A password based AES string encryption utility.
- *
+ * The {@code AESEncryptor} class provides AES encryption and decryption
+ * functionality.
*
- * NOTE: This is a derivative work of https://mkyong.com/java/java-symmetric-key-cryptography-example/
- *
- *
+ * It uses AES/GCM/NoPadding encryption algorithm with a 128-bit tag length,
+ * 12-byte IV length, and 16-byte salt length by default.
+ *
+ * The class provides methods to encrypt and decrypt byte arrays and strings
+ * using the specified password and encryption parameters.
+ *
+ *
+ * NOTE: This is a derivative work of this .
+ *
* @author Anindya Chatterjee
* @since 4.0
*/
@@ -50,12 +57,12 @@ public class AESEncryptor implements Encryptor {
/**
* Instantiates a new {@link AESEncryptor} with these default values
- *
- * Encryption Algo - AES/GCM/NoPadding
- * Tag Length (bit) - 128
- * IV Length (byte) - 12
- * Salt Length (byte) - 16
- *
+ *
+ * Encryption Algo - AES/GCM/NoPadding
+ * Tag Length (bit) - 128
+ * IV Length (byte) - 12
+ * Salt Length (byte) - 16
+ *
*
* @param password the password
*/
@@ -73,8 +80,8 @@ public AESEncryptor(String password) {
* @param saltLengthByte the salt length byte
*/
public AESEncryptor(String password, String encryptionAlgo,
- Integer tagLengthBit, Integer ivLengthByte,
- Integer saltLengthByte) {
+ Integer tagLengthBit, Integer ivLengthByte,
+ Integer saltLengthByte) {
this.password = new SecureString(password);
this.encryptAlgo = encryptionAlgo;
this.tagLengthBit = tagLengthBit;
@@ -109,13 +116,13 @@ public String encrypt(byte[] plainText) {
// prefix IV and Salt to cipher text
byte[] cipherTextWithIvSalt = ByteBuffer.allocate(iv.length + salt.length + cipherText.length)
- .put(iv)
- .put(salt)
- .put(cipherText)
- .array();
+ .put(iv)
+ .put(salt)
+ .put(cipherText)
+ .array();
// string representation, base64, send this string to other for decryption.
- return Base64.encodeToString(cipherTextWithIvSalt, Base64.URL_SAFE);
+ return Base64.encodeBase64URLSafeString(cipherTextWithIvSalt);
} catch (Exception e) {
throw new NitriteSecurityException("Failed to encrypt data", e);
}
@@ -125,15 +132,16 @@ public String encrypt(byte[] plainText) {
* Returns the decrypted string encoded by AES.
*
*
- * NOTE: The same password, salt and iv are needed to decrypt it.
+ * NOTE: The same password, salt and iv are needed to decrypt it.
*
+ *
* @param encryptedText the encrypted text
* @return the plain text decrypted string
*/
@Override
public String decrypt(String encryptedText) {
try {
- byte[] decode = Base64.decode(encryptedText.getBytes(UTF_8), Base64.URL_SAFE);
+ byte[] decode = Base64.decodeBase64(encryptedText);
// get back the iv and salt from the cipher text
ByteBuffer bb = ByteBuffer.wrap(decode);
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/crypto/Encryptor.java b/nitrite-support/src/main/java/org/dizitart/no2/support/crypto/Encryptor.java
similarity index 66%
rename from nitrite/src/main/java/org/dizitart/no2/common/crypto/Encryptor.java
rename to nitrite-support/src/main/java/org/dizitart/no2/support/crypto/Encryptor.java
index 4d32637f5..7c39d6490 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/crypto/Encryptor.java
+++ b/nitrite-support/src/main/java/org/dizitart/no2/support/crypto/Encryptor.java
@@ -15,28 +15,28 @@
*
*/
-package org.dizitart.no2.common.crypto;
+package org.dizitart.no2.support.crypto;
/**
- * Represents a symmetric key string encryptor.
- *
+ * The Encryptor interface provides methods to encrypt and decrypt plain text.
+ *
* @author Anindya Chatterjee
* @since 4.0
*/
public interface Encryptor {
/**
- * Returns a base64 encoded encrypted string.
+ * Encrypts the given plain text using the encryption algorithm.
*
- * @param plainText the plain text
- * @return the encrypted string
+ * @param plainText the plain text to be encrypted
+ * @return the encrypted text
*/
String encrypt(byte[] plainText);
/**
- * Returns the decrypted string, encoded by this encryptor.
+ * Decrypts the given encrypted text.
*
- * @param encryptedText the encrypted text
- * @return the string
+ * @param encryptedText the encrypted text to decrypt
+ * @return the decrypted text
*/
String decrypt(String encryptedText);
}
diff --git a/nitrite-support/src/main/java/org/dizitart/no2/support/exchange/ExportOptions.java b/nitrite-support/src/main/java/org/dizitart/no2/support/exchange/ExportOptions.java
new file mode 100644
index 000000000..ede9cab64
--- /dev/null
+++ b/nitrite-support/src/main/java/org/dizitart/no2/support/exchange/ExportOptions.java
@@ -0,0 +1,151 @@
+/*
+ * Copyright (c) 2017-2020. Nitrite author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.dizitart.no2.support.exchange;
+
+import com.fasterxml.jackson.core.JsonFactory;
+import lombok.Getter;
+import lombok.Setter;
+
+import java.util.*;
+
+/**
+ * The options used for exporting Nitrite database collections and data.
+ *
+ * @author Anindya Chatterjee
+ * @see Exporter
+ * @since 1.0
+ */
+@Getter
+@Setter
+public class ExportOptions {
+ /**
+ * Specifies a {@link NitriteFactory} to create a
+ * {@link org.dizitart.no2.Nitrite} instance. This instance will be used to
+ * export the collections and data.
+ *
+ * The {@link NitriteFactory} instance must be able to create a
+ * {@link org.dizitart.no2.Nitrite}, so the database must not be open elsewhere.
+ * Upon completion of the export operation, the {@link org.dizitart.no2.Nitrite}
+ * instance will be closed.
+ *
+ *
+ * NOTE: This is a mandatory field. If not specified, the export operation will
+ * fail.
+ *
+ * @param nitriteFactory the nitriteFactory.
+ * @return the nitriteFactory.
+ */
+ private NitriteFactory nitriteFactory;
+
+ /**
+ * Specifies a {@link JsonFactory} to create a
+ * {@link com.fasterxml.jackson.core.JsonGenerator} instance.
+ * This instance will be used to write the export data to a file.
+ *
+ * NOTE: This is an optional field. If not specified, a default one will be
+ * created.
+ *
+ * @param jsonFactory the jsonFactory.
+ * @return the jsonFactory.
+ */
+ private JsonFactory jsonFactory;
+
+ /**
+ * Indicates if the export operation exports indices information.
+ *
+ * If true, the export operation will export indices information.
+ * If false, the export operation will not export indices
+ * information.
+ *
+ * This is an optional field. If not specified, it will be set to
+ * true.
+ *
+ * @param exportIndices a value indicating if indices information will be
+ * exported.
+ * @return true if indices information is exported; otherwise,
+ * false.
+ */
+ private boolean exportIndices = true;
+
+ /**
+ * Indicates if the export operation exports collection data.
+ *
+ * If true, the export operation will export collection data. If
+ * false, the export operation will not export collection data.
+ *
+ * This is an optional field. If not specified, it will be set to
+ * true.
+ *
+ * @param exportData a value indicating if collection data will be exported.
+ * @return true if collection data is exported; otherwise,
+ * false.
+ */
+ private boolean exportData = true;
+
+ /**
+ * Specifies a list of {@link org.dizitart.no2.collection.NitriteCollection}
+ * names to be exported.
+ *
+ *
+ * The rules for specifying the collections to be exported as follows:
+ *
+ * If null is specified, all collections will be exported
+ * If an empty list is specified, no collection will be exported
+ * If a non-empty list is specified, only the collections in the list will
+ * be exported
+ *
+ *
+ * @param collections list of all collection names to be exported.
+ * @return list of collection names.
+ */
+ private List collections;
+
+ /**
+ * Specifies a list of {@link org.dizitart.no2.repository.ObjectRepository}
+ * names to be exported.
+ *
+ * The rules for specifying the repositories to be exported as follows:
+ *
+ * If null is specified, all repositories will be exported
+ * If an empty list is specified, no repositories will be exported
+ * If a non-empty list is specified, only the repositories in the list will
+ * be exported
+ *
+ *
+ * @param repositories list of all repositories names to be exported.
+ * @return list of repositories names.
+ */
+ private List repositories;
+
+ /**
+ * Specifies a list of keyed
+ * {@link org.dizitart.no2.repository.ObjectRepository} names to be exported.
+ *
+ * The rules for specifying the keyed-repositories to be exported as
+ * follows:
+ *
+ * If null is specified, all keyed-repositories will be exported
+ * If an empty map is specified, no keyed-repositories will be exported
+ * If a non-empty map is specified, only the keyed-repositories in the map
+ * will be exported
+ *
+ *
+ * @param keyedRepositories list of all keyed repositories names to be exported.
+ * @return list of keyed repositories names.
+ */
+ private Map> keyedRepositories;
+}
diff --git a/nitrite-support/src/main/java/org/dizitart/no2/support/Exporter.java b/nitrite-support/src/main/java/org/dizitart/no2/support/exchange/Exporter.java
similarity index 60%
rename from nitrite-support/src/main/java/org/dizitart/no2/support/Exporter.java
rename to nitrite-support/src/main/java/org/dizitart/no2/support/exchange/Exporter.java
index e8c35e301..12ca97db3 100644
--- a/nitrite-support/src/main/java/org/dizitart/no2/support/Exporter.java
+++ b/nitrite-support/src/main/java/org/dizitart/no2/support/exchange/Exporter.java
@@ -14,97 +14,89 @@
* limitations under the License.
*/
-package org.dizitart.no2.support;
+package org.dizitart.no2.support.exchange;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
-import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
-import org.dizitart.no2.Nitrite;
import org.dizitart.no2.exceptions.NitriteIOException;
import java.io.*;
+import static org.dizitart.no2.common.util.ValidationUtils.notNull;
/**
- * Nitrite database export utility. It exports data to
- * a json file. Contents of a Nitrite database can be exported
- * using this tool.
+ * The Exporter class provides methods to export Nitrite database data to a file
+ * or an output stream in JSON format.
*
- * [[app-listing]]
- * include::/src/docs/asciidoc/tools/data-format.adoc[]
- *
+ * It uses the provided ExportOptions to configure the export process.
+ *
* @author Anindya Chatterjee
* @since 1.0
*/
public class Exporter {
- private Nitrite db;
- private JsonFactory jsonFactory;
private ExportOptions options;
private Exporter() {
}
/**
- * Creates a new {@link Exporter} instance.
+ * Creates an Exporter instance with the specified export options.
+ *
+ * @param exportOptions the export options to be set
+ * (must not be null and must have a valid nitrite factory)
*
- * @param db the db
- * @return the exporter instance
+ * @return the Exporter instance with the specified export options
*/
- public static Exporter of(Nitrite db) {
- return of(db, createObjectMapper());
- }
-
- public static Exporter of(Nitrite db, ObjectMapper objectMapper) {
+ public static Exporter withOptions(ExportOptions exportOptions) {
Exporter exporter = new Exporter();
- exporter.db = db;
- exporter.jsonFactory = objectMapper.getFactory();
- exporter.options = new ExportOptions();
+ notNull(exportOptions, "exportOptions cannot be null");
+ notNull(exportOptions.getNitriteFactory(), "nitriteFactory cannot be null");
+
+ if (exportOptions.getJsonFactory() == null) {
+ exportOptions.setJsonFactory(createObjectMapper().getFactory());
+ }
+
+ exporter.options = exportOptions;
return exporter;
}
+ /**
+ * Creates and returns an instance of ObjectMapper with custom configurations.
+ *
+ * @return an instance of ObjectMapper with custom configurations.
+ */
public static ObjectMapper createObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
- objectMapper.setVisibility(
- objectMapper.getSerializationConfig().getDefaultVisibilityChecker()
- .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
- .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
- .withIsGetterVisibility(JsonAutoDetect.Visibility.NONE));
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ objectMapper.setVisibility(
+ objectMapper.getSerializationConfig().getDefaultVisibilityChecker()
+ .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
+ .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
+ .withIsGetterVisibility(JsonAutoDetect.Visibility.NONE));
return objectMapper;
}
/**
- * Sets {@link ExportOptions} to customize data export.
- *
- * @param options the options
- * @return the exporter
- */
- public Exporter withOptions(ExportOptions options) {
- this.options = options;
- return this;
- }
-
- /**
- * Exports data to a file.
+ * Exports the data to the specified file.
*
- * @param file the file
+ * @param file the file to export the data to
*/
public void exportTo(String file) {
exportTo(new File(file));
}
/**
- * Exports data to a {@link File}.
+ * Exports the content to the specified file.
*
- * @param file the file
- * @throws NitriteIOException if there is any low-level I/O error.
+ * @param file the file to export the content to
+ * @throws NitriteIOException if there is an I/O error while writing content to the file
*/
public void exportTo(File file) {
try {
@@ -129,32 +121,34 @@ public void exportTo(File file) {
}
/**
- * Exports data to an {@link OutputStream}.
+ * Exports the data to the specified output stream.
*
- * @param stream the stream
+ * @param stream the output stream to export the data to
+ * @throws IOException if an I/O error occurs
*/
public void exportTo(OutputStream stream) throws IOException {
- try(OutputStreamWriter writer = new OutputStreamWriter(stream)) {
+ try (OutputStreamWriter writer = new OutputStreamWriter(stream)) {
exportTo(writer);
}
}
/**
- * Exports data to a {@link Writer}.
+ * Exports the data to the specified writer using JSON format.
*
- * @param writer the writer
- * @throws NitriteIOException if there is any error while writing the data.
+ * @param writer the writer to export the data to
+ * @throws NitriteIOException if there is an I/O error while writing data with writer
+ * @throws NitriteIOException if there is an error while exporting data
*/
public void exportTo(Writer writer) {
JsonGenerator generator;
try {
- generator = jsonFactory.createGenerator(writer);
+ generator = options.getJsonFactory().createGenerator(writer);
generator.setPrettyPrinter(new DefaultPrettyPrinter());
} catch (IOException ioe) {
throw new NitriteIOException("I/O error while writing data with writer", ioe);
}
- NitriteJsonExporter jsonExporter = new NitriteJsonExporter(db);
+ NitriteJsonExporter jsonExporter = new NitriteJsonExporter();
jsonExporter.setGenerator(generator);
jsonExporter.setOptions(options);
try {
diff --git a/nitrite-support/src/main/java/org/dizitart/no2/support/exchange/ImportOptions.java b/nitrite-support/src/main/java/org/dizitart/no2/support/exchange/ImportOptions.java
new file mode 100644
index 000000000..c05f67f0f
--- /dev/null
+++ b/nitrite-support/src/main/java/org/dizitart/no2/support/exchange/ImportOptions.java
@@ -0,0 +1,47 @@
+package org.dizitart.no2.support.exchange;
+
+import com.fasterxml.jackson.core.JsonFactory;
+import lombok.Getter;
+import lombok.Setter;
+
+/**
+ * The options for importing collections and data into a Nitrite database.
+ *
+ * @author Anindya Chatterjee
+ * @see Importer
+ * @since 4.0
+ */
+@Getter
+@Setter
+public class ImportOptions {
+ /**
+ * Specifies a {@link NitriteFactory} to create a
+ * {@link org.dizitart.no2.Nitrite} instance. This instance will be used to
+ * export the collections and data.
+ *
+ * The {@link NitriteFactory} instance must be able to create a
+ * {@link org.dizitart.no2.Nitrite}, so the database must not be open elsewhere.
+ * Upon completion of the import operation, the {@link org.dizitart.no2.Nitrite}
+ * instance will be closed.
+ *
+ *
+ * NOTE: This is a mandatory field. If not specified, the import operation will
+ * fail.
+ *
+ * @param nitriteFactory the nitriteFactory.
+ * @return the nitriteFactory.
+ */
+ private NitriteFactory nitriteFactory;
+
+ /**
+ * Specifies a {@link JsonFactory} to create a
+ * {@link com.fasterxml.jackson.core.JsonGenerator} instance.
+ * This instance will be used to read the exported data from a file.
+ *
+ * This is an optional field. If not specified, a default one will be created.
+ *
+ * @param jsonFactory the jsonFactory.
+ * @return the jsonFactory.
+ */
+ private JsonFactory jsonFactory;
+}
diff --git a/nitrite-support/src/main/java/org/dizitart/no2/support/Importer.java b/nitrite-support/src/main/java/org/dizitart/no2/support/exchange/Importer.java
similarity index 52%
rename from nitrite-support/src/main/java/org/dizitart/no2/support/Importer.java
rename to nitrite-support/src/main/java/org/dizitart/no2/support/exchange/Importer.java
index 20b8f52ef..d2bd2ff11 100644
--- a/nitrite-support/src/main/java/org/dizitart/no2/support/Importer.java
+++ b/nitrite-support/src/main/java/org/dizitart/no2/support/exchange/Importer.java
@@ -14,58 +14,56 @@
* limitations under the License.
*/
-package org.dizitart.no2.support;
+package org.dizitart.no2.support.exchange;
-import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import org.dizitart.no2.Nitrite;
import org.dizitart.no2.exceptions.NitriteIOException;
+import org.dizitart.no2.exceptions.ValidationException;
import java.io.*;
-import static org.dizitart.no2.support.Exporter.createObjectMapper;
-
+import static org.dizitart.no2.common.util.ValidationUtils.notNull;
+import static org.dizitart.no2.support.exchange.Exporter.createObjectMapper;
/**
- * Nitrite database import utility. It imports data from
- * a json file. Contents of a Nitrite database can be imported
- * using this tool.
+ * The Importer class provides methods to import data from a file or stream into
+ * Nitrite database.
*
- * [[app-listing]]
- * include::/src/docs/asciidoc/tools/data-format.adoc[]
- *
+ * It uses the provided ImportOptions to configure the import process.
+ *
* @author Anindya Chatterjee
* @since 1.0
*/
public class Importer {
- private Nitrite db;
- private JsonFactory jsonFactory;
+ private ImportOptions options;
private Importer() {
}
/**
- * Creates a new {@link Importer} instance.
+ * Creates a new instance of {@link Importer} with the specified import options.
*
- * @param db the db
- * @return the importer instance
+ * @param importOptions the import options to use
+ * @return a new instance of {@link Importer} with the specified import options
+ * @throws ValidationException if the import options or nitrite factory is null
*/
- public static Importer of(Nitrite db) {
- return of(db, createObjectMapper());
- }
-
- public static Importer of(Nitrite db, ObjectMapper objectMapper) {
+ public static Importer withOptions(ImportOptions importOptions) {
Importer importer = new Importer();
- importer.db = db;
- importer.jsonFactory = objectMapper.getFactory();
+ notNull(importOptions, "importOptions cannot be null");
+ notNull(importOptions.getNitriteFactory(), "nitriteFactory cannot be null");
+
+ if (importOptions.getJsonFactory() == null) {
+ importOptions.setJsonFactory(createObjectMapper().getFactory());
+ }
+
+ importer.options = importOptions;
return importer;
}
/**
- * Imports data from a file path.
+ * Imports data from the specified file.
*
- * @param file the file path
+ * @param file the file to import data from
*/
public void importFrom(String file) {
importFrom(new File(file));
@@ -74,8 +72,8 @@ public void importFrom(String file) {
/**
* Imports data from a file.
*
- * @param file the file
- * @throws NitriteIOException if there is any low-level I/O error.
+ * @param file the file to import data from
+ * @throws NitriteIOException if there is an I/O error while reading content from the file
*/
public void importFrom(File file) {
try (FileInputStream stream = new FileInputStream(file)) {
@@ -86,33 +84,35 @@ public void importFrom(File file) {
}
/**
- * Imports data from an {@link InputStream}.
+ * Imports data from the specified input stream.
*
- * @param stream the stream
+ * @param stream the input stream to import data from
+ * @throws IOException if an I/O error occurs
*/
public void importFrom(InputStream stream) throws IOException {
- try(InputStreamReader reader = new InputStreamReader(stream)) {
+ try (InputStreamReader reader = new InputStreamReader(stream)) {
importFrom(reader);
}
}
/**
- * Imports data from a {@link Reader}.
+ * Imports data from a Reader object using a JSON parser.
*
- * @param reader the reader
- * @throws NitriteIOException if there is any error while reading the data.
+ * @param reader the Reader object to import data from
+ * @throws NitriteIOException if there is an I/O error while creating the parser from the reader or while importing data
*/
public void importFrom(Reader reader) {
JsonParser parser;
try {
- parser = jsonFactory.createParser(reader);
+ parser = options.getJsonFactory().createParser(reader);
} catch (IOException ioe) {
throw new NitriteIOException("I/O error while creating parser from reader", ioe);
}
if (parser != null) {
- NitriteJsonImporter jsonImporter = new NitriteJsonImporter(db);
+ NitriteJsonImporter jsonImporter = new NitriteJsonImporter();
jsonImporter.setParser(parser);
+ jsonImporter.setOptions(options);
try {
jsonImporter.importData();
} catch (IOException | ClassNotFoundException e) {
diff --git a/nitrite-support/src/main/java/org/dizitart/no2/support/exchange/NitriteFactory.java b/nitrite-support/src/main/java/org/dizitart/no2/support/exchange/NitriteFactory.java
new file mode 100644
index 000000000..4bf1b5efb
--- /dev/null
+++ b/nitrite-support/src/main/java/org/dizitart/no2/support/exchange/NitriteFactory.java
@@ -0,0 +1,20 @@
+package org.dizitart.no2.support.exchange;
+
+import org.dizitart.no2.Nitrite;
+
+/**
+ * A functional interface for creating a {@link Nitrite} instance.
+ *
+ * @since 4.0
+ * @see Nitrite
+ * @author Anindya Chatterjee
+ */
+@FunctionalInterface
+public interface NitriteFactory {
+ /**
+ * Creates a new instance of Nitrite database.
+ *
+ * @return a new instance of Nitrite database.
+ */
+ Nitrite create();
+}
diff --git a/nitrite-support/src/main/java/org/dizitart/no2/support/exchange/NitriteJsonExporter.java b/nitrite-support/src/main/java/org/dizitart/no2/support/exchange/NitriteJsonExporter.java
new file mode 100644
index 000000000..04cfd0e35
--- /dev/null
+++ b/nitrite-support/src/main/java/org/dizitart/no2/support/exchange/NitriteJsonExporter.java
@@ -0,0 +1,205 @@
+/*
+ * Copyright (c) 2017-2020. Nitrite author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+ package org.dizitart.no2.support.exchange;
+
+import com.fasterxml.jackson.core.JsonGenerator;
+import lombok.Setter;
+import org.apache.commons.codec.binary.Base64;
+import org.dizitart.no2.Nitrite;
+import org.dizitart.no2.collection.Document;
+import org.dizitart.no2.collection.NitriteId;
+import org.dizitart.no2.collection.operation.IndexManager;
+import org.dizitart.no2.common.tuples.Pair;
+import org.dizitart.no2.exceptions.NitriteIOException;
+import org.dizitart.no2.index.IndexDescriptor;
+import org.dizitart.no2.store.NitriteMap;
+import org.dizitart.no2.store.NitriteStore;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectOutputStream;
+import java.util.*;
+import java.util.stream.Collectors;
+
+import static org.dizitart.no2.common.Constants.*;
+import static org.dizitart.no2.common.util.ObjectUtils.findRepositoryName;
+
+ /**
+ * @author Anindya Chatterjee
+ */
+ @Setter
+ class NitriteJsonExporter {
+ private JsonGenerator generator;
+ private ExportOptions options;
+
+ public void exportData() throws IOException, ClassNotFoundException {
+ try(Nitrite db = options.getNitriteFactory().create()) {
+ Set collectionNames = options.getCollections() == null ? db.listCollectionNames() : new HashSet<>();
+ Set repositoryNames = options.getRepositories() == null ? db.listRepositories() : new HashSet<>();
+ Map> keyedRepositoryNames = options.getKeyedRepositories() == null
+ ? db.listKeyedRepositories() : new HashMap<>();
+
+ List indexDescriptors = new ArrayList<>();
+ if (options.getCollections() != null && !options.getCollections().isEmpty()) {
+ collectionNames = new HashSet<>(options.getCollections());
+ }
+
+ if (options.getRepositories() != null && !options.getRepositories().isEmpty()) {
+ repositoryNames = new HashSet<>(options.getRepositories());
+ }
+
+ if (options.getKeyedRepositories() != null && !options.getKeyedRepositories().isEmpty()) {
+ keyedRepositoryNames = options.getKeyedRepositories();
+ }
+
+ if (options.isExportIndices()) {
+ for (String collectionName : collectionNames) {
+ try(IndexManager indexManager = new IndexManager(collectionName, db.getConfig())) {
+ indexDescriptors.addAll(indexManager.getIndexDescriptors());
+ }
+ }
+
+ for (String repositoryName : repositoryNames) {
+ try(IndexManager indexManager = new IndexManager(repositoryName, db.getConfig())) {
+ indexDescriptors.addAll(indexManager.getIndexDescriptors());
+ }
+ }
+
+ for (Map.Entry> entry : keyedRepositoryNames.entrySet()) {
+ String key = entry.getKey();
+ Set entityNameSet = entry.getValue();
+ for (String entityName : entityNameSet) {
+ String repositoryName = findRepositoryName(key, entityName);
+ try(IndexManager indexManager = new IndexManager(repositoryName, db.getConfig())) {
+ indexDescriptors.addAll(indexManager.getIndexDescriptors());
+ }
+ }
+ }
+ }
+
+ exportData(db, collectionNames, repositoryNames, keyedRepositoryNames, indexDescriptors);
+ generator.close();
+ }
+ }
+
+ private void exportData(Nitrite db,
+ Set collectionNames,
+ Set repositoryNames,
+ Map> keyedRepositoryNames,
+ List indexDescriptors) throws IOException {
+ NitriteStore> nitriteStore = db.getStore();
+
+ generator.writeStartObject();
+
+ writeMaps(collectionNames, indexDescriptors, nitriteStore, TAG_COLLECTIONS);
+
+ writeMaps(repositoryNames, indexDescriptors, nitriteStore, TAG_REPOSITORIES);
+
+ writeKeyedMaps(keyedRepositoryNames, indexDescriptors, nitriteStore);
+
+ generator.writeEndObject();
+ }
+
+ private void writeMaps(Set mapNames, List indexDescriptors,
+ NitriteStore> nitriteStore, String tagName) throws IOException {
+ generator.writeFieldName(tagName);
+ generator.writeStartArray();
+ for (String mapName : mapNames) {
+ try(NitriteMap nitriteMap
+ = nitriteStore.openMap(mapName, NitriteId.class, Document.class)) {
+ List indexes = indexDescriptors.stream().filter(d ->
+ mapName.equalsIgnoreCase(d.getCollectionName())).collect(Collectors.toList());
+ writeNitriteMap(nitriteMap, indexes);
+ }
+ }
+ generator.writeEndArray();
+ }
+
+ private void writeKeyedMaps(Map> keyedMapNames, List indexDescriptors,
+ NitriteStore> nitriteStore) throws IOException {
+ generator.writeFieldName(TAG_KEYED_REPOSITORIES);
+ generator.writeStartArray();
+ for (Map.Entry> entry : keyedMapNames.entrySet()) {
+ String key = entry.getKey();
+ Set typeNames = entry.getValue();
+ for (String typeName : typeNames) {
+ String repoName = findRepositoryName(typeName, key);
+ try(NitriteMap nitriteMap
+ = nitriteStore.openMap(repoName, NitriteId.class, Document.class)) {
+ List indexes = indexDescriptors.stream().filter(d ->
+ repoName.equalsIgnoreCase(d.getCollectionName())).collect(Collectors.toList());
+ writeNitriteMap(nitriteMap, indexes);
+ }
+ }
+ }
+ generator.writeEndArray();
+ }
+
+ private void writeNitriteMap(NitriteMap nitriteMap,
+ List indexes) throws IOException {
+ generator.writeStartObject();
+ generator.writeFieldName(TAG_NAME);
+ generator.writeString(nitriteMap.getName());
+ writeIndices(indexes);
+ writeContent(nitriteMap);
+ generator.writeEndObject();
+ }
+
+ private void writeIndices(Collection indices) throws IOException {
+ generator.writeFieldName(TAG_INDICES);
+ generator.writeStartArray();
+ if (options.isExportIndices()) {
+ for (IndexDescriptor index : indices) {
+ generator.writeStartObject();
+ generator.writeFieldName(TAG_INDEX);
+ generator.writeObject(writeEncodedObject(index));
+ generator.writeEndObject();
+ }
+ }
+ generator.writeEndArray();
+ }
+
+ private void writeContent(NitriteMap nitriteMap) throws IOException {
+ generator.writeFieldName(TAG_DATA);
+ generator.writeStartArray();
+ if (options.isExportData()) {
+ for (Pair entry : nitriteMap.entries()) {
+ generator.writeStartObject();
+ generator.writeFieldName(TAG_KEY);
+ generator.writeObject(writeEncodedObject(entry.getFirst()));
+
+ generator.writeFieldName(TAG_VALUE);
+ generator.writeObject(writeEncodedObject(entry.getSecond()));
+ generator.writeEndObject();
+ }
+ }
+ generator.writeEndArray();
+ }
+
+ private String writeEncodedObject(Object object) {
+ try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
+ try (ObjectOutputStream oos = new ObjectOutputStream(os)) {
+ oos.writeObject(object);
+ byte[] data = os.toByteArray();
+ return Base64.encodeBase64URLSafeString(data);
+ }
+ } catch (IOException e) {
+ throw new NitriteIOException("Failed to write object", e);
+ }
+ }
+ }
+
\ No newline at end of file
diff --git a/nitrite-support/src/main/java/org/dizitart/no2/support/exchange/NitriteJsonImporter.java b/nitrite-support/src/main/java/org/dizitart/no2/support/exchange/NitriteJsonImporter.java
new file mode 100644
index 000000000..32bc275d5
--- /dev/null
+++ b/nitrite-support/src/main/java/org/dizitart/no2/support/exchange/NitriteJsonImporter.java
@@ -0,0 +1,171 @@
+/*
+ * Copyright (c) 2017-2020. Nitrite author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.dizitart.no2.support.exchange;
+
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonToken;
+import lombok.Setter;
+import org.apache.commons.codec.binary.Base64;
+import org.dizitart.no2.Nitrite;
+import org.dizitart.no2.collection.Document;
+import org.dizitart.no2.collection.NitriteId;
+import org.dizitart.no2.collection.operation.IndexManager;
+import org.dizitart.no2.exceptions.NitriteIOException;
+import org.dizitart.no2.index.IndexDescriptor;
+import org.dizitart.no2.store.NitriteMap;
+import org.dizitart.no2.store.NitriteStore;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.dizitart.no2.common.Constants.*;
+
+/**
+ * @author Anindya Chatterjee.
+ */
+@Setter
+class NitriteJsonImporter {
+ private JsonParser parser;
+ private ImportOptions options;
+
+ public void importData() throws IOException, ClassNotFoundException {
+ try (Nitrite db = options.getNitriteFactory().create()) {
+ while (parser.nextToken() != JsonToken.END_OBJECT) {
+ String fieldName = parser.getCurrentName();
+
+ if (TAG_COLLECTIONS.equals(fieldName)) {
+ readNitriteMap(db);
+ }
+
+ if (TAG_REPOSITORIES.equals(fieldName)) {
+ readNitriteMap(db);
+ }
+
+ if (TAG_KEYED_REPOSITORIES.equals(fieldName)) {
+ readNitriteMap(db);
+ }
+ }
+ }
+ }
+
+ private void readNitriteMap(Nitrite db) throws IOException {
+ // move to [
+ parser.nextToken();
+ NitriteStore> nitriteStore = db.getStore();
+
+ // loop till token equal to "]"
+ while (parser.nextToken() != JsonToken.END_ARRAY) {
+ // loop until end of collection object
+ NitriteMap nitriteMap = null;
+ List indexDescriptors = new ArrayList<>();
+
+ while (parser.nextToken() != JsonToken.END_OBJECT) {
+ String fieldName = parser.getCurrentName();
+
+ if (TAG_NAME.equals(fieldName)) {
+ // move to next token
+ parser.nextToken();
+
+ String mapName = parser.getText();
+ nitriteMap = nitriteStore.openMap(mapName, NitriteId.class, Document.class);
+ }
+
+ if (TAG_INDICES.equals(fieldName)) {
+ indexDescriptors = readIndices();
+ }
+
+ if (TAG_DATA.equals(fieldName) && nitriteMap != null) {
+ readNitriteMapData(nitriteMap);
+
+ // write index information
+ try (IndexManager indexManager = new IndexManager(nitriteMap.getName(), db.getConfig())) {
+ // during next data insertion, index will be rebuilt
+ indexDescriptors.forEach(indexManager::markIndexDirty);
+ }
+ }
+ }
+ }
+ }
+
+ private List readIndices() throws IOException {
+ List indexDescriptors = new ArrayList<>();
+ // move to [
+ parser.nextToken();
+
+ // loop till token equal to "]"
+ while (parser.nextToken() != JsonToken.END_ARRAY) {
+ // loop until end of collection object
+ while (parser.nextToken() != JsonToken.END_OBJECT) {
+ String fieldName = parser.getCurrentName();
+
+ if (TAG_INDEX.equals(fieldName)) {
+ parser.nextToken();
+ String data = parser.readValueAs(String.class);
+ IndexDescriptor index = readEncodedObject(data, IndexDescriptor.class);
+ indexDescriptors.add(index);
+ }
+ }
+ }
+ return indexDescriptors;
+ }
+
+ private void readNitriteMapData(NitriteMap nitriteMap) throws IOException {
+ // move to [
+ parser.nextToken();
+
+ // loop till token equal to "]"
+ while (parser.nextToken() != JsonToken.END_ARRAY) {
+ // loop until end of collection object
+ NitriteId nitriteId = null;
+ while (parser.nextToken() != JsonToken.END_OBJECT) {
+ String fieldName = parser.getCurrentName();
+
+ if (TAG_KEY.equals(fieldName)) {
+ parser.nextToken();
+ String data = parser.readValueAs(String.class);
+ nitriteId = readEncodedObject(data, NitriteId.class);
+ }
+
+ if (TAG_VALUE.equals(fieldName)) {
+ parser.nextToken();
+ String data = parser.readValueAs(String.class);
+ Document document = readEncodedObject(data, Document.class);
+ if (nitriteMap != null) {
+ nitriteMap.put(nitriteId, document);
+ }
+ }
+ }
+ }
+ }
+
+ private T readEncodedObject(String encodedString, Class type) {
+ try {
+ byte[] data = Base64.decodeBase64(encodedString);
+ try (ByteArrayInputStream is = new ByteArrayInputStream(data)) {
+ try (ObjectInputStream ois = new ObjectInputStream(is)) {
+ return type.cast(ois.readObject());
+ }
+ }
+ } catch (Exception e) {
+ throw new NitriteIOException("Error while reading data", e);
+ }
+ }
+}
+
\ No newline at end of file
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/processors/StringFieldEncryptionProcessor.java b/nitrite-support/src/main/java/org/dizitart/no2/support/processors/StringFieldEncryptionProcessor.java
similarity index 72%
rename from nitrite/src/main/java/org/dizitart/no2/common/processors/StringFieldEncryptionProcessor.java
rename to nitrite-support/src/main/java/org/dizitart/no2/support/processors/StringFieldEncryptionProcessor.java
index ccf6a8a46..78f74434e 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/processors/StringFieldEncryptionProcessor.java
+++ b/nitrite-support/src/main/java/org/dizitart/no2/support/processors/StringFieldEncryptionProcessor.java
@@ -15,14 +15,15 @@
*
*/
-package org.dizitart.no2.common.processors;
+package org.dizitart.no2.support.processors;
import lombok.extern.slf4j.Slf4j;
import org.dizitart.no2.collection.Document;
-import org.dizitart.no2.common.crypto.AESEncryptor;
-import org.dizitart.no2.common.crypto.Encryptor;
+import org.dizitart.no2.common.processors.Processor;
import org.dizitart.no2.common.util.StringUtils;
import org.dizitart.no2.exceptions.NitriteIOException;
+import org.dizitart.no2.support.crypto.AESEncryptor;
+import org.dizitart.no2.support.crypto.Encryptor;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
@@ -30,13 +31,13 @@
import java.util.List;
/**
- * A string field encryption processor. It encrypts the field value
- * of type {@link String} in a nitrite document using the provided {@link Encryptor}.
- *
+ * A processor class which is responsible for encrypting and
+ * decrypting string fields in a Nitrite database document.
+ *
* @author Anindya Chatterjee
* @since 4.0
*/
-@Slf4j
+@Slf4j(topic = "nitrite-support")
public class StringFieldEncryptionProcessor implements Processor {
private final Encryptor encryptor;
private final List fields;
@@ -61,14 +62,22 @@ public StringFieldEncryptionProcessor(Encryptor encryptor) {
}
/**
- * Adds fields for encryption.
+ * Adds one or more field names to the list of fields that should be encrypted.
*
- * @param fields the fields
+ * @param fields the names of the fields to be encrypted
*/
- public void addFields(String... fields){
+ public void addFields(String... fields) {
this.fields.addAll(Arrays.asList(fields));
}
+ /**
+ * Processes the document before writing to the database. Encrypts the values of the specified fields
+ * using the provided encryptor.
+ *
+ * @param document the document to be processed
+ * @return a new document with encrypted values for the specified fields
+ * @throws NitriteIOException if there is an error while processing the document
+ */
@Override
public Document processBeforeWrite(Document document) {
try {
@@ -92,6 +101,14 @@ public Document processBeforeWrite(Document document) {
}
}
+ /**
+ * Processes the document after reading from the database. Decrypts the encrypted fields
+ * and returns a new document with decrypted values.
+ *
+ * @param document the document to be processed
+ * @return a new document with decrypted values
+ * @throws NitriteIOException if there is an error while processing the document
+ */
@Override
public Document processAfterRead(Document document) {
try {
diff --git a/nitrite-support/src/test/java/org/dizitart/no2/support/BaseExternalTest.java b/nitrite-support/src/test/java/org/dizitart/no2/support/BaseExternalTest.java
deleted file mode 100644
index 98a84d3a5..000000000
--- a/nitrite-support/src/test/java/org/dizitart/no2/support/BaseExternalTest.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Copyright (c) 2017-2020. Nitrite author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.dizitart.no2.support;
-
-import org.dizitart.no2.Nitrite;
-import org.dizitart.no2.collection.Document;
-import org.dizitart.no2.collection.NitriteCollection;
-import org.dizitart.no2.common.mapper.SimpleDocumentMapper;
-import org.dizitart.no2.mvstore.MVStoreModule;
-import org.dizitart.no2.repository.ObjectRepository;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Rule;
-
-import java.io.File;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Paths;
-import java.util.List;
-import java.util.UUID;
-
-import static org.dizitart.no2.common.Constants.*;
-import static org.dizitart.no2.common.util.Iterables.setOf;
-import static org.junit.Assert.assertTrue;
-
-/**
- * @author Anindya Chatterjee.
- */
-public abstract class BaseExternalTest {
- protected ObjectRepository sourceEmpRepo;
- protected ObjectRepository sourceKeyedEmpRepo;
- protected ObjectRepository sourceCompRepo;
- protected NitriteCollection sourceFirstColl;
- protected NitriteCollection sourceSecondColl;
- protected Nitrite sourceDb;
- protected Nitrite destDb;
- protected String schemaFile;
- private String sourceDbFile;
- private String destDbFile;
-
- @Rule
- public Retry retry = new Retry(3);
-
- public static String getRandomTempDbFile() {
- String dataDir = System.getProperty("java.io.tmpdir") + File.separator + "nitrite" + File.separator + "data";
- File file = new File(dataDir);
- if (!file.exists()) {
- assertTrue(file.mkdirs());
- }
- return file.getPath() + File.separator + UUID.randomUUID() + ".db";
- }
-
- @Before
- public void setUp() {
- sourceDbFile = getRandomTempDbFile();
- destDbFile = getRandomTempDbFile();
-
- sourceDb = createDb(sourceDbFile);
-
- destDb = createDb(destDbFile);
-
- sourceEmpRepo = sourceDb.getRepository(Employee.class);
- sourceKeyedEmpRepo = sourceDb.getRepository(Employee.class, "key");
- sourceCompRepo = sourceDb.getRepository(Company.class);
-
- sourceFirstColl = sourceDb.getCollection("first");
- sourceSecondColl = sourceDb.getCollection("second");
- }
-
- @After
- public void cleanUp() throws IOException {
- sourceFirstColl.close();
- sourceSecondColl.close();
- sourceEmpRepo.close();
- sourceCompRepo.close();
-
- sourceDb.close();
- destDb.close();
-
- Files.delete(Paths.get(sourceDbFile));
- Files.delete(Paths.get(destDbFile));
- Files.delete(Paths.get(schemaFile));
- }
-
- protected List filter(List documents) {
- for (Document document : documents) {
- document.remove(DOC_REVISION);
- document.remove(DOC_MODIFIED);
- document.remove(DOC_SOURCE);
- }
- return documents;
- }
-
- private Nitrite createDb(String filePath) {
- MVStoreModule storeModule = MVStoreModule.withConfig()
- .filePath(filePath)
- .build();
-
- SimpleDocumentMapper documentMapper = new SimpleDocumentMapper();
- documentMapper.registerEntityConverter(new Employee.EmployeeConverter());
- documentMapper.registerEntityConverter(new Company.CompanyConverter());
- documentMapper.registerEntityConverter(new Note.NoteConverter());
-
- return Nitrite.builder()
- .loadModule(storeModule)
- .loadModule(() -> setOf(documentMapper))
- .fieldSeparator(".")
- .openOrCreate();
- }
-}
diff --git a/nitrite-support/src/test/java/org/dizitart/no2/support/ExporterImporterOptionTest.java b/nitrite-support/src/test/java/org/dizitart/no2/support/ExporterImporterOptionTest.java
deleted file mode 100644
index 1523eff59..000000000
--- a/nitrite-support/src/test/java/org/dizitart/no2/support/ExporterImporterOptionTest.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Copyright (c) 2017-2020. Nitrite author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.dizitart.no2.support;
-
-import org.dizitart.no2.collection.Document;
-import org.dizitart.no2.collection.NitriteCollection;
-import org.dizitart.no2.common.PersistentCollection;
-import org.dizitart.no2.index.IndexDescriptor;
-import org.dizitart.no2.repository.ObjectRepository;
-import org.junit.Test;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.LinkedHashSet;
-import java.util.Random;
-
-import static org.dizitart.no2.collection.Document.createDocument;
-import static org.junit.Assert.assertEquals;
-
-/**
- * @author Anindya Chatterjee.
- */
-public class ExporterImporterOptionTest extends BaseExternalTest {
-
- @Test
- public void testImportExportSingle() {
- schemaFile = System.getProperty("java.io.tmpdir") + File.separator
- + "nitrite" + File.separator + "single-schema.json";
-
- Random random = new Random();
- for (int i = 0; i < 5; i++) {
- sourceEmpRepo.insert(DataGenerator.generateEmployee());
- sourceKeyedEmpRepo.insert(DataGenerator.generateEmployee());
-
- Document document = createDocument("first-field", random.nextGaussian());
- sourceFirstColl.insert(document);
- }
-
- Exporter exporter = Exporter.of(sourceDb);
- exporter.withOptions(new ExportOptions() {{
- setCollections(new ArrayList>() {{
- add(sourceEmpRepo);
- add(sourceKeyedEmpRepo);
- add(sourceFirstColl);
- }});
- }});
- exporter.exportTo(schemaFile);
-
- Importer importer = Importer.of(destDb);
- importer.importFrom(schemaFile);
-
- ObjectRepository destEmpRepo = destDb.getRepository(Employee.class);
- ObjectRepository destKeyedEmpRepo = destDb.getRepository(Employee.class, "key");
- NitriteCollection destFirstColl = destDb.getCollection("first");
-
- assertEquals(filter(sourceFirstColl.find().toList()),
- filter(destFirstColl.find().toList()));
- assertEquals(sourceEmpRepo.find().toList(),
- destEmpRepo.find().toList());
- assertEquals(sourceKeyedEmpRepo.find().toList(),
- destKeyedEmpRepo.find().toList());
-
- assertEquals(sourceEmpRepo.listIndices(), destEmpRepo.listIndices());
- assertEquals(sourceKeyedEmpRepo.listIndices(), destKeyedEmpRepo.listIndices());
- assertEquals(sourceFirstColl.listIndices(), destFirstColl.listIndices());
-
- ObjectRepository destCompRepo = destDb.getRepository(Company.class);
- NitriteCollection destSecondColl = destDb.getCollection("second");
-
- assertEquals(filter(destSecondColl.find().toList()),
- new ArrayList());
- assertEquals(destCompRepo.find().toList(),
- new ArrayList());
-
- assertEquals(destCompRepo.listIndices(), sourceCompRepo.listIndices());
- assertEquals(destSecondColl.listIndices(), new LinkedHashSet());
- }
-}
diff --git a/nitrite-support/src/test/java/org/dizitart/no2/support/ExporterImporterTest.java b/nitrite-support/src/test/java/org/dizitart/no2/support/ExporterImporterTest.java
deleted file mode 100644
index 2f6dd5014..000000000
--- a/nitrite-support/src/test/java/org/dizitart/no2/support/ExporterImporterTest.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (c) 2017-2020. Nitrite author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.dizitart.no2.support;
-
-import org.dizitart.no2.collection.Document;
-import org.dizitart.no2.collection.NitriteCollection;
-import org.dizitart.no2.repository.ObjectRepository;
-import org.junit.Test;
-
-import java.io.File;
-import java.util.Random;
-
-import static org.dizitart.no2.collection.Document.createDocument;
-import static org.junit.Assert.assertEquals;
-
-/**
- * @author Anindya Chatterjee.
- */
-public class ExporterImporterTest extends BaseExternalTest {
-
- @Test
- public void testImportExport() {
- schemaFile = System.getProperty("java.io.tmpdir") + File.separator
- + "nitrite" + File.separator + "schema.json";
-
- Random random = new Random();
- for (int i = 0; i < 5; i++) {
- sourceEmpRepo.insert(DataGenerator.generateEmployee());
- sourceKeyedEmpRepo.insert(DataGenerator.generateEmployee());
- sourceCompRepo.insert(DataGenerator.generateCompanyRecord());
-
- Document document = createDocument("first-field", random.nextGaussian());
- sourceFirstColl.insert(document);
-
- document = createDocument("second-field", random.nextLong());
- sourceSecondColl.insert(document);
- }
-
- Exporter exporter = Exporter.of(sourceDb);
- exporter.exportTo(schemaFile);
-
- Importer importer = Importer.of(destDb);
- importer.importFrom(schemaFile);
-
- NitriteCollection destFirstColl = destDb.getCollection("first");
- NitriteCollection destSecondColl = destDb.getCollection("second");
- ObjectRepository destEmpRepo = destDb.getRepository(Employee.class);
- ObjectRepository destKeyedEmpRepo = destDb.getRepository(Employee.class, "key");
- ObjectRepository destCompRepo = destDb.getRepository(Company.class);
-
- assertEquals(filter(sourceFirstColl.find().toList()),
- filter(destFirstColl.find().toList()));
- assertEquals(filter(sourceSecondColl.find().toList()),
- filter(destSecondColl.find().toList()));
-
- assertEquals(sourceEmpRepo.find().toList(),
- destEmpRepo.find().toList());
- assertEquals(sourceKeyedEmpRepo.find().toList(),
- destKeyedEmpRepo.find().toList());
- assertEquals(sourceCompRepo.find().toList(),
- destCompRepo.find().toList());
-
- assertEquals(sourceEmpRepo.listIndices(), destEmpRepo.listIndices());
- assertEquals(sourceKeyedEmpRepo.listIndices(), destKeyedEmpRepo.listIndices());
- assertEquals(sourceCompRepo.listIndices(), destCompRepo.listIndices());
- assertEquals(sourceFirstColl.listIndices(), destFirstColl.listIndices());
- assertEquals(sourceSecondColl.listIndices(), destSecondColl.listIndices());
- }
-}
diff --git a/nitrite-support/src/test/java/org/dizitart/no2/support/Retry.java b/nitrite-support/src/test/java/org/dizitart/no2/support/Retry.java
index 98b478557..3d491a127 100644
--- a/nitrite-support/src/test/java/org/dizitart/no2/support/Retry.java
+++ b/nitrite-support/src/test/java/org/dizitart/no2/support/Retry.java
@@ -1,5 +1,6 @@
package org.dizitart.no2.support;
+import lombok.extern.slf4j.Slf4j;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
@@ -7,6 +8,7 @@
/**
* @author Anindya Chatterjee
*/
+@Slf4j
public class Retry implements TestRule {
private final int retryCount;
@@ -31,12 +33,14 @@ public void evaluate() throws Throwable {
return;
} catch (Throwable t) {
caughtThrowable = t;
- System.err.println(description.getDisplayName() + ": run " + (i + 1) + " failed");
+ log.warn(description.getDisplayName() + ": run " + (i + 1) + " failed");
}
}
- System.err.println(description.getDisplayName() + ": giving up after " + retryCount + " failures");
- throw caughtThrowable;
+ log.error(description.getDisplayName() + ": giving up after " + retryCount + " failures");
+ if (caughtThrowable != null) {
+ throw caughtThrowable;
+ }
}
};
}
-}
+}
\ No newline at end of file
diff --git a/nitrite-support/src/test/java/org/dizitart/no2/support/TestUtil.java b/nitrite-support/src/test/java/org/dizitart/no2/support/TestUtil.java
new file mode 100644
index 000000000..2aa2d3050
--- /dev/null
+++ b/nitrite-support/src/test/java/org/dizitart/no2/support/TestUtil.java
@@ -0,0 +1,214 @@
+/*
+ * Copyright (c) 2017-2021 Nitrite author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package org.dizitart.no2.support;
+
+import com.fasterxml.jackson.annotation.JsonAutoDetect;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.dizitart.no2.Nitrite;
+import org.dizitart.no2.collection.Document;
+import org.dizitart.no2.exceptions.ObjectMappingException;
+import org.dizitart.no2.mvstore.MVStoreModule;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.*;
+
+import static org.junit.Assert.assertTrue;
+
+/**
+ * @author Anindya Chatterjee
+ */
+@Slf4j
+public class TestUtil {
+
+ public static String getRandomTempDbFile() {
+ String dataDir = System.getProperty("java.io.tmpdir") + File.separator + "nitrite" + File.separator + "data";
+ File file = new File(dataDir);
+ if (!file.exists()) {
+ assertTrue(file.mkdirs());
+ }
+ return file.getPath() + File.separator + UUID.randomUUID() + ".db";
+ }
+
+ public static void deleteDb(String filePath) {
+ try {
+ Files.delete(Paths.get(filePath));
+ } catch (Exception e) {
+ log.error("Error while deleting db", e);
+ }
+ }
+
+ public static > boolean isSorted(Iterable iterable, boolean ascending) {
+ Iterator iterator = iterable.iterator();
+ if (!iterator.hasNext()) {
+ return true;
+ }
+ T t = iterator.next();
+ while (iterator.hasNext()) {
+ T t2 = iterator.next();
+ if (ascending) {
+ if (t.compareTo(t2) > 0) {
+ return false;
+ }
+ } else {
+ if (t.compareTo(t2) < 0) {
+ return false;
+ }
+ }
+ t = t2;
+ }
+ return true;
+ }
+
+ public static Nitrite createDb() {
+ MVStoreModule storeModule = MVStoreModule.withConfig()
+ .build();
+
+ return Nitrite.builder()
+ .loadModule(storeModule)
+ .fieldSeparator(".")
+ .openOrCreate();
+ }
+
+ public static Nitrite createDb(String user, String password) {
+ MVStoreModule storeModule = MVStoreModule.withConfig()
+ .build();
+
+ return Nitrite.builder()
+ .loadModule(storeModule)
+ .fieldSeparator(".")
+ .openOrCreate(user, password);
+ }
+
+ public static Nitrite createDb(String filePath) {
+ MVStoreModule storeModule = MVStoreModule.withConfig()
+ .filePath(filePath)
+ .compress(true)
+ .build();
+
+ return Nitrite.builder()
+ .loadModule(storeModule)
+ .fieldSeparator(".")
+ .openOrCreate();
+ }
+
+ public static Nitrite createDb(String filePath, String user, String password) {
+ MVStoreModule storeModule = MVStoreModule.withConfig()
+ .filePath(filePath)
+ .compress(true)
+ .build();
+
+ return Nitrite.builder()
+ .loadModule(storeModule)
+ .fieldSeparator(".")
+ .openOrCreate(user, password);
+ }
+
+ public static Document parse(String json) {
+ try {
+ ObjectMapper objectMapper = createObjectMapper();
+ JsonNode node = objectMapper.readValue(json, JsonNode.class);
+ return loadDocument(node);
+ } catch (IOException e) {
+ log.error("Error while parsing json", e);
+ throw new ObjectMappingException("failed to parse json " + json);
+ }
+ }
+
+ private static Document loadDocument(JsonNode node) {
+ Map objectMap = new LinkedHashMap<>();
+ Iterator> fields = node.fields();
+ while (fields.hasNext()) {
+ Map.Entry entry = fields.next();
+ String name = entry.getKey();
+ JsonNode value = entry.getValue();
+ Object object = loadObject(value);
+ objectMap.put(name, object);
+ }
+
+ return Document.createDocument(objectMap);
+ }
+
+ private static Object loadObject(JsonNode node) {
+ if (node == null)
+ return null;
+ try {
+ switch (node.getNodeType()) {
+ case ARRAY:
+ return loadArray(node);
+ case BINARY:
+ return node.binaryValue();
+ case BOOLEAN:
+ return node.booleanValue();
+ case MISSING:
+ case NULL:
+ return null;
+ case NUMBER:
+ return node.numberValue();
+ case OBJECT:
+ case POJO:
+ return loadDocument(node);
+ case STRING:
+ return node.textValue();
+ }
+ } catch (IOException e) {
+ return null;
+ }
+ return null;
+ }
+
+ @SuppressWarnings({"unchecked", "rawtypes"})
+ private static List loadArray(JsonNode array) {
+ if (array.isArray()) {
+ List list = new ArrayList();
+ Iterator iterator = array.elements();
+ while (iterator.hasNext()) {
+ Object element = iterator.next();
+ if (element instanceof JsonNode) {
+ list.add(loadObject((JsonNode) element));
+ } else {
+ list.add(element);
+ }
+ }
+ return list;
+ }
+ return null;
+ }
+
+ private static ObjectMapper createObjectMapper() {
+ ObjectMapper objectMapper = new ObjectMapper();
+ objectMapper.setVisibility(
+ objectMapper.getSerializationConfig().getDefaultVisibilityChecker()
+ .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
+ .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
+ .withIsGetterVisibility(JsonAutoDetect.Visibility.NONE));
+ objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
+ objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
+ objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
+ objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+
+ objectMapper.findAndRegisterModules();
+ return objectMapper;
+ }
+}
diff --git a/nitrite/src/test/java/org/dizitart/no2/common/crypto/AESEncryptorTest.java b/nitrite-support/src/test/java/org/dizitart/no2/support/crypto/AESEncryptorTest.java
similarity index 96%
rename from nitrite/src/test/java/org/dizitart/no2/common/crypto/AESEncryptorTest.java
rename to nitrite-support/src/test/java/org/dizitart/no2/support/crypto/AESEncryptorTest.java
index 854bff17b..79678a522 100644
--- a/nitrite/src/test/java/org/dizitart/no2/common/crypto/AESEncryptorTest.java
+++ b/nitrite-support/src/test/java/org/dizitart/no2/support/crypto/AESEncryptorTest.java
@@ -15,7 +15,7 @@
*
*/
-package org.dizitart.no2.common.crypto;
+package org.dizitart.no2.support.crypto;
import org.dizitart.no2.exceptions.NitriteSecurityException;
import org.junit.Test;
diff --git a/nitrite-support/src/test/java/org/dizitart/no2/support/Company.java b/nitrite-support/src/test/java/org/dizitart/no2/support/data/Company.java
similarity index 98%
rename from nitrite-support/src/test/java/org/dizitart/no2/support/Company.java
rename to nitrite-support/src/test/java/org/dizitart/no2/support/data/Company.java
index d66f8254f..f49d93e55 100644
--- a/nitrite-support/src/test/java/org/dizitart/no2/support/Company.java
+++ b/nitrite-support/src/test/java/org/dizitart/no2/support/data/Company.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.dizitart.no2.support;
+package org.dizitart.no2.support.data;
import lombok.Data;
import org.dizitart.no2.collection.Document;
diff --git a/nitrite-support/src/test/java/org/dizitart/no2/support/DataGenerator.java b/nitrite-support/src/test/java/org/dizitart/no2/support/data/DataGenerator.java
similarity index 98%
rename from nitrite-support/src/test/java/org/dizitart/no2/support/DataGenerator.java
rename to nitrite-support/src/test/java/org/dizitart/no2/support/data/DataGenerator.java
index acea54ef5..225a6a7b9 100644
--- a/nitrite-support/src/test/java/org/dizitart/no2/support/DataGenerator.java
+++ b/nitrite-support/src/test/java/org/dizitart/no2/support/data/DataGenerator.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.dizitart.no2.support;
+package org.dizitart.no2.support.data;
import com.github.javafaker.Faker;
import lombok.experimental.UtilityClass;
diff --git a/nitrite-support/src/test/java/org/dizitart/no2/support/Employee.java b/nitrite-support/src/test/java/org/dizitart/no2/support/data/Employee.java
similarity index 98%
rename from nitrite-support/src/test/java/org/dizitart/no2/support/Employee.java
rename to nitrite-support/src/test/java/org/dizitart/no2/support/data/Employee.java
index f05767e09..5c7ed6d4d 100644
--- a/nitrite-support/src/test/java/org/dizitart/no2/support/Employee.java
+++ b/nitrite-support/src/test/java/org/dizitart/no2/support/data/Employee.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.dizitart.no2.support;
+package org.dizitart.no2.support.data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
diff --git a/nitrite-support/src/test/java/org/dizitart/no2/support/Note.java b/nitrite-support/src/test/java/org/dizitart/no2/support/data/Note.java
similarity index 97%
rename from nitrite-support/src/test/java/org/dizitart/no2/support/Note.java
rename to nitrite-support/src/test/java/org/dizitart/no2/support/data/Note.java
index ee3435060..32e7dbe84 100644
--- a/nitrite-support/src/test/java/org/dizitart/no2/support/Note.java
+++ b/nitrite-support/src/test/java/org/dizitart/no2/support/data/Note.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.dizitart.no2.support;
+package org.dizitart.no2.support.data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
diff --git a/nitrite-support/src/test/java/org/dizitart/no2/support/exchange/BaseExternalTest.java b/nitrite-support/src/test/java/org/dizitart/no2/support/exchange/BaseExternalTest.java
new file mode 100644
index 000000000..2fd3324fb
--- /dev/null
+++ b/nitrite-support/src/test/java/org/dizitart/no2/support/exchange/BaseExternalTest.java
@@ -0,0 +1,133 @@
+/*
+ * Copyright (c) 2017-2020. Nitrite author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+ package org.dizitart.no2.support.exchange;
+
+import org.dizitart.no2.Nitrite;
+import org.dizitart.no2.collection.Document;
+import org.dizitart.no2.collection.NitriteCollection;
+import org.dizitart.no2.common.mapper.SimpleNitriteMapper;
+import org.dizitart.no2.mvstore.MVStoreModule;
+import org.dizitart.no2.repository.ObjectRepository;
+import org.dizitart.no2.support.Retry;
+import org.dizitart.no2.support.TestUtil;
+import org.dizitart.no2.support.data.Company;
+import org.dizitart.no2.support.data.Employee;
+import org.dizitart.no2.support.data.Note;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+import java.util.UUID;
+
+import static org.dizitart.no2.common.Constants.*;
+import static org.dizitart.no2.common.module.NitriteModule.module;
+import static org.junit.Assert.assertTrue;
+
+ /**
+ * @author Anindya Chatterjee.
+ */
+ public abstract class BaseExternalTest {
+ protected ObjectRepository sourceEmpRepo;
+ protected ObjectRepository sourceKeyedEmpRepo;
+ protected ObjectRepository sourceCompRepo;
+ protected NitriteCollection sourceFirstColl;
+ protected NitriteCollection sourceSecondColl;
+ protected Nitrite sourceDb;
+ protected Nitrite destDb;
+ protected String schemaFile;
+ protected String sourceDbFile;
+ protected String destDbFile;
+
+ @Rule
+ public Retry retry = new Retry(3);
+
+ @Before
+ public void setUp() {
+ sourceDbFile = getRandomTempDbFile();
+ destDbFile = getRandomTempDbFile();
+ openDb();
+ }
+
+ @After
+ public void cleanUp() throws IOException {
+ closeDb();
+ TestUtil.deleteDb(sourceDbFile);
+ TestUtil.deleteDb(destDbFile);
+ TestUtil.deleteDb(schemaFile);
+ }
+
+ public static String getRandomTempDbFile() {
+ String dataDir = System.getProperty("java.io.tmpdir") + File.separator + "nitrite" + File.separator + "data";
+ File file = new File(dataDir);
+ if (!file.exists()) {
+ assertTrue(file.mkdirs());
+ }
+ return file.getPath() + File.separator + UUID.randomUUID() + ".db";
+ }
+
+ protected void openDb() {
+ sourceDb = createDb(sourceDbFile);
+ destDb = createDb(destDbFile);
+
+ sourceEmpRepo = sourceDb.getRepository(Employee.class);
+ sourceKeyedEmpRepo = sourceDb.getRepository(Employee.class, "key");
+ sourceCompRepo = sourceDb.getRepository(Company.class);
+
+ sourceFirstColl = sourceDb.getCollection("first");
+ sourceSecondColl = sourceDb.getCollection("second");
+ }
+
+ protected void closeDb() {
+ sourceFirstColl.close();
+ sourceSecondColl.close();
+ sourceEmpRepo.close();
+ sourceCompRepo.close();
+
+ sourceDb.close();
+ destDb.close();
+ }
+
+ protected List filter(List documents) {
+ for (Document document : documents) {
+ document.remove(DOC_REVISION);
+ document.remove(DOC_MODIFIED);
+ document.remove(DOC_SOURCE);
+ }
+ return documents;
+ }
+
+ protected Nitrite createDb(String filePath) {
+ MVStoreModule storeModule = MVStoreModule.withConfig()
+ .filePath(filePath)
+ .build();
+
+ SimpleNitriteMapper documentMapper = new SimpleNitriteMapper();
+ documentMapper.registerEntityConverter(new Employee.EmployeeConverter());
+ documentMapper.registerEntityConverter(new Company.CompanyConverter());
+ documentMapper.registerEntityConverter(new Note.NoteConverter());
+
+ return Nitrite.builder()
+ .loadModule(storeModule)
+ .loadModule(module(documentMapper))
+ .fieldSeparator(".")
+ .openOrCreate();
+ }
+ }
+
\ No newline at end of file
diff --git a/nitrite-support/src/test/java/org/dizitart/no2/support/ExportOptionsTest.java b/nitrite-support/src/test/java/org/dizitart/no2/support/exchange/ExportOptionsTest.java
similarity index 54%
rename from nitrite-support/src/test/java/org/dizitart/no2/support/ExportOptionsTest.java
rename to nitrite-support/src/test/java/org/dizitart/no2/support/exchange/ExportOptionsTest.java
index a286fb1d2..0cac9a283 100644
--- a/nitrite-support/src/test/java/org/dizitart/no2/support/ExportOptionsTest.java
+++ b/nitrite-support/src/test/java/org/dizitart/no2/support/exchange/ExportOptionsTest.java
@@ -1,21 +1,12 @@
-package org.dizitart.no2.support;
+package org.dizitart.no2.support.exchange;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
-import java.util.ArrayList;
-
-import org.dizitart.no2.common.PersistentCollection;
+import org.dizitart.no2.support.exchange.ExportOptions;
import org.junit.Test;
public class ExportOptionsTest {
- @Test
- public void testSetCollections() {
- ExportOptions exportOptions = new ExportOptions();
- ArrayList> persistentCollectionList = new ArrayList>();
- exportOptions.setCollections(persistentCollectionList);
- assertSame(persistentCollectionList, exportOptions.getCollections());
- }
@Test
public void testSetExportData() {
diff --git a/nitrite-support/src/test/java/org/dizitart/no2/support/exchange/ExporterImporterOptionTest.java b/nitrite-support/src/test/java/org/dizitart/no2/support/exchange/ExporterImporterOptionTest.java
new file mode 100644
index 000000000..60996f47f
--- /dev/null
+++ b/nitrite-support/src/test/java/org/dizitart/no2/support/exchange/ExporterImporterOptionTest.java
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) 2017-2020. Nitrite author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+ package org.dizitart.no2.support.exchange;
+
+ import org.dizitart.no2.collection.Document;
+ import org.dizitart.no2.collection.NitriteCollection;
+ import org.dizitart.no2.index.IndexDescriptor;
+ import org.dizitart.no2.repository.ObjectRepository;
+ import org.dizitart.no2.support.data.Company;
+ import org.dizitart.no2.support.data.DataGenerator;
+ import org.dizitart.no2.support.data.Employee;
+ import org.junit.Test;
+
+ import java.io.File;
+ import java.util.*;
+
+ import static org.dizitart.no2.collection.Document.createDocument;
+ import static org.junit.Assert.assertEquals;
+
+ /**
+ * @author Anindya Chatterjee.
+ */
+ public class ExporterImporterOptionTest extends BaseExternalTest {
+
+ @Test
+ public void testImportExportSingle() {
+ schemaFile = System.getProperty("java.io.tmpdir") + File.separator
+ + "nitrite" + File.separator + "single-schema.json";
+
+ Random random = new Random();
+ for (int i = 0; i < 5; i++) {
+ sourceEmpRepo.insert(DataGenerator.generateEmployee());
+ sourceKeyedEmpRepo.insert(DataGenerator.generateEmployee());
+
+ Document document = createDocument("first-field", random.nextGaussian());
+ sourceFirstColl.insert(document);
+ }
+ closeDb();
+
+ ExportOptions exportOptions = new ExportOptions();
+ exportOptions.setNitriteFactory(() -> createDb(sourceDbFile));
+ exportOptions.setCollections(List.of("first"));
+ exportOptions.setRepositories(List.of("org.dizitart.no2.support.data.Employee"));
+ exportOptions.setKeyedRepositories(Map.of("key", Set.of("org.dizitart.no2.support.data.Employee")));
+
+ Exporter exporter = Exporter.withOptions(exportOptions);
+ exporter.exportTo(schemaFile);
+
+ ImportOptions importOptions = new ImportOptions();
+ importOptions.setNitriteFactory(() -> createDb(destDbFile));
+
+ Importer importer = Importer.withOptions(importOptions);
+ importer.importFrom(schemaFile);
+
+ openDb();
+
+ ObjectRepository destEmpRepo = destDb.getRepository(Employee.class);
+ ObjectRepository destKeyedEmpRepo = destDb.getRepository(Employee.class, "key");
+ NitriteCollection destFirstColl = destDb.getCollection("first");
+
+ assertEquals(filter(sourceFirstColl.find().toList()),
+ filter(destFirstColl.find().toList()));
+ assertEquals(sourceEmpRepo.find().toList(),
+ destEmpRepo.find().toList());
+ assertEquals(sourceKeyedEmpRepo.find().toList(),
+ destKeyedEmpRepo.find().toList());
+
+ assertEquals(sourceEmpRepo.listIndices(), destEmpRepo.listIndices());
+ assertEquals(sourceKeyedEmpRepo.listIndices(), destKeyedEmpRepo.listIndices());
+ assertEquals(sourceFirstColl.listIndices(), destFirstColl.listIndices());
+
+ ObjectRepository destCompRepo = destDb.getRepository(Company.class);
+ NitriteCollection destSecondColl = destDb.getCollection("second");
+
+ assertEquals(filter(destSecondColl.find().toList()),
+ new ArrayList());
+ assertEquals(destCompRepo.find().toList(),
+ new ArrayList());
+
+ assertEquals(destCompRepo.listIndices(), sourceCompRepo.listIndices());
+ assertEquals(destSecondColl.listIndices(), new LinkedHashSet());
+ }
+ }
+
\ No newline at end of file
diff --git a/nitrite-support/src/test/java/org/dizitart/no2/support/exchange/ExporterImporterTest.java b/nitrite-support/src/test/java/org/dizitart/no2/support/exchange/ExporterImporterTest.java
new file mode 100644
index 000000000..2805d5c1a
--- /dev/null
+++ b/nitrite-support/src/test/java/org/dizitart/no2/support/exchange/ExporterImporterTest.java
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) 2017-2020. Nitrite author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+ package org.dizitart.no2.support.exchange;
+
+ import org.dizitart.no2.collection.Document;
+ import org.dizitart.no2.collection.NitriteCollection;
+ import org.dizitart.no2.repository.ObjectRepository;
+ import org.dizitart.no2.support.data.Company;
+ import org.dizitart.no2.support.data.DataGenerator;
+ import org.dizitart.no2.support.data.Employee;
+ import org.junit.Test;
+
+ import java.io.File;
+ import java.util.List;
+ import java.util.Map;
+ import java.util.Random;
+ import java.util.Set;
+
+ import static org.dizitart.no2.collection.Document.createDocument;
+ import static org.junit.Assert.*;
+
+ /**
+ * @author Anindya Chatterjee.
+ */
+ public class ExporterImporterTest extends BaseExternalTest {
+
+ @Test
+ public void testImportExport() {
+ schemaFile = System.getProperty("java.io.tmpdir") + File.separator
+ + "nitrite" + File.separator + "schema.json";
+
+ Random random = new Random();
+ for (int i = 0; i < 5; i++) {
+ sourceEmpRepo.insert(DataGenerator.generateEmployee());
+ sourceKeyedEmpRepo.insert(DataGenerator.generateEmployee());
+ sourceCompRepo.insert(DataGenerator.generateCompanyRecord());
+
+ Document document = createDocument("first-field", random.nextGaussian());
+ sourceFirstColl.insert(document);
+
+ document = createDocument("second-field", random.nextLong());
+ sourceSecondColl.insert(document);
+ }
+ closeDb();
+
+ ExportOptions exportOptions = new ExportOptions();
+ exportOptions.setNitriteFactory(() -> createDb(sourceDbFile));
+ exportOptions.setCollections(List.of("first"));
+ exportOptions.setRepositories(List.of("org.dizitart.no2.support.data.Employee", "org.dizitart.no2.support.data.Company"));
+ exportOptions.setKeyedRepositories(Map.of("key", Set.of("org.dizitart.no2.support.data.Employee")));
+
+ Exporter exporter = Exporter.withOptions(exportOptions);
+ exporter.exportTo(schemaFile);
+
+ ImportOptions importOptions = new ImportOptions();
+ importOptions.setNitriteFactory(() -> createDb(destDbFile));
+
+ Importer importer = Importer.withOptions(importOptions);
+ importer.importFrom(schemaFile);
+
+ openDb();
+
+ NitriteCollection destFirstColl = destDb.getCollection("first");
+ NitriteCollection destSecondColl = destDb.getCollection("second");
+ ObjectRepository destEmpRepo = destDb.getRepository(Employee.class);
+ ObjectRepository destKeyedEmpRepo = destDb.getRepository(Employee.class, "key");
+ ObjectRepository destCompRepo = destDb.getRepository(Company.class);
+
+ assertEquals(filter(sourceFirstColl.find().toList()),
+ filter(destFirstColl.find().toList()));
+ assertNotEquals(filter(sourceSecondColl.find().toList()),
+ filter(destSecondColl.find().toList()));
+ assertTrue(destSecondColl.find().isEmpty());
+
+ assertEquals(sourceEmpRepo.find().toList(),
+ destEmpRepo.find().toList());
+ assertEquals(sourceKeyedEmpRepo.find().toList(),
+ destKeyedEmpRepo.find().toList());
+ assertEquals(sourceCompRepo.find().toList(),
+ destCompRepo.find().toList());
+
+ assertEquals(sourceEmpRepo.listIndices(), destEmpRepo.listIndices());
+ assertEquals(sourceKeyedEmpRepo.listIndices(), destKeyedEmpRepo.listIndices());
+ assertEquals(sourceCompRepo.listIndices(), destCompRepo.listIndices());
+ assertEquals(sourceFirstColl.listIndices(), destFirstColl.listIndices());
+ assertEquals(0, destSecondColl.listIndices().size());
+ }
+ }
+
\ No newline at end of file
diff --git a/nitrite-support/src/test/java/org/dizitart/no2/support/ExporterTest.java b/nitrite-support/src/test/java/org/dizitart/no2/support/exchange/ExporterTest.java
similarity index 97%
rename from nitrite-support/src/test/java/org/dizitart/no2/support/ExporterTest.java
rename to nitrite-support/src/test/java/org/dizitart/no2/support/exchange/ExporterTest.java
index cd6b7c23e..e8a7b8e60 100644
--- a/nitrite-support/src/test/java/org/dizitart/no2/support/ExporterTest.java
+++ b/nitrite-support/src/test/java/org/dizitart/no2/support/exchange/ExporterTest.java
@@ -1,4 +1,4 @@
-package org.dizitart.no2.support;
+package org.dizitart.no2.support.exchange;
import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -10,6 +10,7 @@
import com.fasterxml.jackson.databind.jsontype.impl.StdSubtypeResolver;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.type.TypeFactory;
+import org.dizitart.no2.support.exchange.Exporter;
import org.junit.Test;
import static org.junit.Assert.*;
diff --git a/nitrite-support/src/test/java/org/dizitart/no2/support/GithubIssueTest.java b/nitrite-support/src/test/java/org/dizitart/no2/support/exchange/GithubIssueTest.java
similarity index 77%
rename from nitrite-support/src/test/java/org/dizitart/no2/support/GithubIssueTest.java
rename to nitrite-support/src/test/java/org/dizitart/no2/support/exchange/GithubIssueTest.java
index c819f3f20..c94839374 100644
--- a/nitrite-support/src/test/java/org/dizitart/no2/support/GithubIssueTest.java
+++ b/nitrite-support/src/test/java/org/dizitart/no2/support/exchange/GithubIssueTest.java
@@ -1,4 +1,4 @@
-package org.dizitart.no2.support;
+package org.dizitart.no2.support.exchange;
import lombok.Data;
import org.dizitart.no2.Nitrite;
@@ -14,6 +14,7 @@
import org.dizitart.no2.mvstore.MVStoreModule;
import org.dizitart.no2.repository.Cursor;
import org.dizitart.no2.repository.ObjectRepository;
+import org.dizitart.no2.repository.annotations.Entity;
import org.dizitart.no2.repository.annotations.Id;
import org.junit.Test;
@@ -23,8 +24,9 @@
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
+import java.util.List;
-import static org.dizitart.no2.support.BaseExternalTest.getRandomTempDbFile;
+import static org.dizitart.no2.support.exchange.BaseExternalTest.getRandomTempDbFile;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@@ -73,13 +75,22 @@ public void testIssue819() throws IOException {
assertTrue(value instanceof Long);
widgetRepo.createIndex(IndexOptions.indexOptions(IndexType.NON_UNIQUE), "localDateEpochDay");
-
- // export the db
- Exporter exporter = Exporter.of(db);
- exporter.exportTo(exportFilePath);
}
+ // export the db
+ ExportOptions exportOptions = new ExportOptions();
+ exportOptions.setNitriteFactory(() -> createDb(initialDbPath));
+ exportOptions.setRepositories(List.of("widget"));
+ Exporter exporter = Exporter.withOptions(exportOptions);
+ exporter.exportTo(exportFilePath);
+
// import the db
+ ImportOptions importOptions = new ImportOptions();
+ importOptions.setNitriteFactory(() -> createDb(importedDbPath));
+ Importer importer = Importer.withOptions(importOptions);
+ importer.importFrom(exportFilePath);
+
+ // open the imported db
storeModule = MVStoreModule.withConfig()
.filePath(importedDbPath)
.build();
@@ -89,8 +100,6 @@ public void testIssue819() throws IOException {
.loadModule(new JacksonMapperModule())
.fieldSeparator(".")
.openOrCreate()) {
- Importer importer = Importer.of(db);
- importer.importFrom(exportFilePath);
// retrieve the widget as a Document to check the stored type
ObjectRepository widgetRepo = db.getRepository(Widget.class);
@@ -120,11 +129,23 @@ public void testIssue819() throws IOException {
Files.deleteIfExists(path2);
}
+ private Nitrite createDb(String path) {
+ MVStoreModule storeModule = MVStoreModule.withConfig()
+ .filePath(path)
+ .build();
+
+ return Nitrite.builder()
+ .loadModule(storeModule)
+ .loadModule(new JacksonMapperModule())
+ .fieldSeparator(".")
+ .openOrCreate();
+ }
+
@Data
+ @Entity(value = "widget")
static class Widget {
@Id
- NitriteId id;
- Long localDateEpochDay;
+ private NitriteId id;
+ private Long localDateEpochDay;
}
-
}
diff --git a/nitrite-support/src/test/java/org/dizitart/no2/support/processors/BaseCollectionTest.java b/nitrite-support/src/test/java/org/dizitart/no2/support/processors/BaseCollectionTest.java
new file mode 100644
index 000000000..867ff9808
--- /dev/null
+++ b/nitrite-support/src/test/java/org/dizitart/no2/support/processors/BaseCollectionTest.java
@@ -0,0 +1,168 @@
+/*
+ * Copyright (c) 2017-2021 Nitrite author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package org.dizitart.no2.support.processors;
+
+import lombok.extern.slf4j.Slf4j;
+import org.dizitart.no2.Nitrite;
+import org.dizitart.no2.NitriteBuilder;
+import org.dizitart.no2.collection.Document;
+import org.dizitart.no2.collection.NitriteCollection;
+import org.dizitart.no2.common.WriteResult;
+import org.dizitart.no2.mvstore.MVStoreModule;
+import org.dizitart.no2.mvstore.MVStoreModuleBuilder;
+import org.dizitart.no2.support.Retry;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import java.text.SimpleDateFormat;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Locale;
+
+import static org.dizitart.no2.collection.Document.createDocument;
+import static org.dizitart.no2.filters.Filter.ALL;
+import static org.dizitart.no2.support.TestUtil.deleteDb;
+import static org.dizitart.no2.support.TestUtil.getRandomTempDbFile;
+
+@Slf4j
+@RunWith(value = Parameterized.class)
+public abstract class BaseCollectionTest {
+ @Parameterized.Parameter
+ public boolean inMemory = false;
+ @Parameterized.Parameter(value = 1)
+ public boolean isSecured = false;
+ @Parameterized.Parameter(value = 2)
+ public boolean isCompressed = false;
+ @Parameterized.Parameter(value = 3)
+ public boolean isAutoCommit = false;
+
+ protected Nitrite db;
+ protected NitriteCollection collection;
+ protected Document doc1, doc2, doc3;
+ protected SimpleDateFormat simpleDateFormat;
+ private final String fileName = getRandomTempDbFile();
+
+ @Rule
+ public Retry retry = new Retry(3);
+
+ @Parameterized.Parameters(name = "InMemory = {0}, Secured = {1}, " +
+ "Compressed = {2}, AutoCommit = {3}, AutoCompact = {4}")
+ public static Collection data() {
+ return Arrays.asList(new Object[][]{
+ {false, false, false, false},
+ {false, false, false, true},
+ {false, false, true, false},
+ {false, false, true, true},
+ {false, true, false, false},
+ {false, true, false, true},
+ {false, true, true, false},
+ {false, true, true, true},
+ {true, false, false, false},
+ {true, false, false, true},
+ {true, false, true, false},
+ {true, false, true, true},
+ {true, true, false, false},
+ {true, true, false, true},
+ {true, true, true, false},
+ {true, true, true, true},
+ });
+ }
+
+ @Before
+ public void setUp() {
+ try {
+ openDb();
+
+ simpleDateFormat
+ = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
+
+ doc1 = createDocument("firstName", "fn1")
+ .put("lastName", "ln1")
+ .put("birthDay", simpleDateFormat.parse("2012-07-01T16:02:48.440Z"))
+ .put("data", new byte[]{1, 2, 3})
+ .put("list", Arrays.asList("one", "two", "three"))
+ .put("body", "a quick brown fox jump over the lazy dog");
+ doc2 = createDocument("firstName", "fn2")
+ .put("lastName", "ln2")
+ .put("birthDay", simpleDateFormat.parse("2010-06-12T16:02:48.440Z"))
+ .put("data", new byte[]{3, 4, 3})
+ .put("list", Arrays.asList("three", "four", "five"))
+ .put("body", "quick hello world from nitrite");
+ doc3 = createDocument("firstName", "fn3")
+ .put("lastName", "ln2")
+ .put("birthDay", simpleDateFormat.parse("2014-04-17T16:02:48.440Z"))
+ .put("data", new byte[]{9, 4, 8})
+ .put("body", "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
+ "Sed nunc mi, mattis ullamcorper dignissim vitae, condimentum non lorem.");
+
+ collection = db.getCollection("test");
+ collection.remove(ALL);
+ } catch (Throwable t) {
+ log.error("Error while initializing test database", t);
+ }
+ }
+
+ @After
+ public void clear() {
+ try {
+ if (collection != null && !collection.isDropped()) {
+ collection.close();
+ }
+ if (db != null && !db.isClosed()) db.close();
+ if (!inMemory) {
+ deleteDb(fileName);
+ }
+ } catch (Throwable t) {
+ log.error("Error while clearing test database", t);
+ }
+ }
+
+ private void openDb() {
+ MVStoreModuleBuilder builder = MVStoreModule.withConfig();
+
+ if (isCompressed) {
+ builder.compress(true);
+ }
+
+ if (!isAutoCommit) {
+ builder.autoCommit(false);
+ }
+
+ if (!inMemory) {
+ builder.filePath(fileName);
+ }
+
+ MVStoreModule storeModule = builder.build();
+ NitriteBuilder nitriteBuilder = Nitrite.builder()
+ .fieldSeparator(".")
+ .loadModule(storeModule);
+
+ if (isSecured) {
+ db = nitriteBuilder.openOrCreate("test-user", "test-password");
+ } else {
+ db = nitriteBuilder.openOrCreate();
+ }
+ }
+
+ protected WriteResult insert() {
+ return collection.insert(doc1, doc2, doc3);
+ }
+}
diff --git a/nitrite/src/test/java/org/dizitart/no2/integration/collection/FieldProcessorTest.java b/nitrite-support/src/test/java/org/dizitart/no2/support/processors/FieldProcessorTest.java
similarity index 93%
rename from nitrite/src/test/java/org/dizitart/no2/integration/collection/FieldProcessorTest.java
rename to nitrite-support/src/test/java/org/dizitart/no2/support/processors/FieldProcessorTest.java
index 08cf8fc9f..578fa7104 100644
--- a/nitrite/src/test/java/org/dizitart/no2/integration/collection/FieldProcessorTest.java
+++ b/nitrite-support/src/test/java/org/dizitart/no2/support/processors/FieldProcessorTest.java
@@ -15,18 +15,17 @@
*
*/
-package org.dizitart.no2.integration.collection;
+package org.dizitart.no2.support.processors;
import org.dizitart.no2.collection.Document;
import org.dizitart.no2.collection.NitriteCollection;
import org.dizitart.no2.collection.NitriteId;
import org.dizitart.no2.common.WriteResult;
-import org.dizitart.no2.common.crypto.AESEncryptor;
-import org.dizitart.no2.common.crypto.Encryptor;
import org.dizitart.no2.common.processors.Processor;
-import org.dizitart.no2.common.processors.StringFieldEncryptionProcessor;
import org.dizitart.no2.exceptions.NitriteSecurityException;
import org.dizitart.no2.store.NitriteMap;
+import org.dizitart.no2.support.crypto.AESEncryptor;
+import org.dizitart.no2.support.crypto.Encryptor;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
@@ -46,14 +45,13 @@ public class FieldProcessorTest extends BaseCollectionTest {
private Encryptor encryptor;
private NitriteCollection collection;
- private Processor cvvProcessor;
@Before
public void setUp() {
super.setUp();
encryptor = new AESEncryptor("s3k4e8");
- cvvProcessor = new Processor() {
+ Processor cvvProcessor = new Processor() {
@Override
public Document processBeforeWrite(Document document) {
String cvv = document.get("cvv", String.class);
@@ -94,10 +92,12 @@ public Document processAfterRead(Document document) {
@Test
public void testFieldEncryptionInNitriteMap() {
- NitriteMap nitriteMap = collection.getStore().openMap("encryption-test",
- NitriteId.class, Document.class);
+ List documents;
+ try (NitriteMap nitriteMap = collection.getStore().openMap("encryption-test",
+ NitriteId.class, Document.class)) {
- List documents = toList(nitriteMap.values());
+ documents = toList(nitriteMap.values());
+ }
for (Document document : documents) {
if (document.get("creditCardNumber", String.class).equalsIgnoreCase("5548960345687452")) {
Assert.fail("unencrypted secret text found");
diff --git a/nitrite/pom.xml b/nitrite/pom.xml
index b4ffaeb52..0515d8a25 100644
--- a/nitrite/pom.xml
+++ b/nitrite/pom.xml
@@ -43,6 +43,10 @@
lombok
provided
+
+ commons-codec
+ commons-codec
+
junit
@@ -134,10 +138,65 @@
org.jacoco
jacoco-maven-plugin
+
+
+ **/index/fulltext/languages/*
+
+
org.apache.maven.plugins
maven-javadoc-plugin
+
+
+ org.dizitart.no2.collection.operation,
+ org.dizitart.no2.common.concurrent,
+ org.dizitart.no2.common.event,
+ org.dizitart.no2.common.streams,
+ org.dizitart.no2.common.util,
+ org.dizitart.no2.index.fulltext.languages,
+ org.dizitart.no2.migration.commands,
+ org.dizitart.no2.store.memory,
+
+
+ **/*Factory.java
+ **/*DefaultNitriteCollection.java
+ **/*SnowflakeIdGenerator.java
+ **/*AttributesAware.java
+ **/*PluginManager.java
+ **/*ProcessorChain.java
+ **/*Constants.java
+ **/*DBNull.java
+ **/*DBValue.java
+ **/*UnknownType.java
+ **/*AndFilter.java
+ **/*OrFilter.java
+ **/*BetweenFilter.java
+ **/*ComparableArrayFilter.java
+ **/*ElementMatchFilter.java
+ **/*EqualsFilter.java
+ **/*TextFilter.java
+ **/*ComparableIndexer.java
+ **/*CompoundIndex.java
+ **/*IndexMap.java
+ **/*IndexMeta.java
+ **/*IndexScanner.java
+ **/*NitriteTextIndexer.java
+ **/*NonUniqueIndexer.java
+ **/*SingleFieldIndex.java
+ **/*TextIndex.java
+ **/*UniqueIndexer.java
+ **/*MigrationManager.java
+ **/*EntityDecoratorScanner.java
+ **/*IndexValidator.java
+ **/*ObjectCursor.java
+ **/*RepositoryOperations.java
+ **/*EventBus.java
+ **/*MetaData.java
+ **/*UserAuthenticationService.java
+ **/*UserCredential.java
+
+
org.apache.maven.plugins
diff --git a/nitrite/src/main/java/org/dizitart/no2/Nitrite.java b/nitrite/src/main/java/org/dizitart/no2/Nitrite.java
index cd5a39fa1..62689b596 100644
--- a/nitrite/src/main/java/org/dizitart/no2/Nitrite.java
+++ b/nitrite/src/main/java/org/dizitart/no2/Nitrite.java
@@ -37,18 +37,33 @@
import static org.dizitart.no2.common.util.ValidationUtils.notNull;
/**
- * An in-memory, single-file based embedded nosql persistent document store. The store
- * can contains multiple named document collections.
+ * Nitrite is a lightweight, embedded, and self-contained Java NoSQL database.
+ * It provides an easy-to-use API to store and retrieve data. Nitrite stores
+ * data in the form of documents and supports indexing on fields within
+ * the documents to provide efficient search capabilities. Nitrite supports
+ * transactions, and provides a simple and efficient way to persist data.
*
+ *
+ * Nitrite is thread-safe and can be used in a multi-threaded environment
+ * without any issues. Nitrite is designed to be embedded within the application
+ * and does not require any external setup or installation.
+ *
+ *
+ * @see NitriteBuilder
+ * @see NitriteCollection
+ * @see ObjectRepository
+ * @see EntityDecorator
+ *
* @author Anindya Chatterjee
* @since 1.0
*/
public interface Nitrite extends AutoCloseable {
/**
- * Returns an instance of a {@link NitriteBuilder}.
+ * Returns a new instance of {@link NitriteBuilder} to build a new Nitrite
+ * database instance.
*
- * @return the nitrite builder
+ * @return a new instance of {@link NitriteBuilder}.
*/
static NitriteBuilder builder() {
return new NitriteBuilder();
@@ -74,11 +89,11 @@ static NitriteBuilder builder() {
* The name cannot contain below reserved strings:
*
*
- * {@link Constants#INTERNAL_NAME_SEPARATOR}
- * {@link Constants#USER_MAP}
- * {@link Constants#INDEX_META_PREFIX}
- * {@link Constants#INDEX_PREFIX}
- * {@link Constants#OBJECT_STORE_NAME_SEPARATOR}
+ * {@link Constants#INTERNAL_NAME_SEPARATOR}
+ * {@link Constants#USER_MAP}
+ * {@link Constants#INDEX_META_PREFIX}
+ * {@link Constants#INDEX_PREFIX}
+ * {@link Constants#OBJECT_STORE_NAME_SEPARATOR}
*
*
* @param name the name of the collection
@@ -102,9 +117,9 @@ static NitriteBuilder builder() {
ObjectRepository getRepository(Class type);
/**
- * Opens a type-safe object repository with a key identifier from the store. If the repository
- * does not exist it will be created automatically and returned. If a
- * repository is already opened, it is returned as is.
+ * Opens a type-safe object repository with a key identifier from the store.
+ * If the repository does not exist it will be created automatically and
+ * returned. If a repository is already opened, it is returned as is.
*
* The returned repository is thread-safe for concurrent use.
*
@@ -117,28 +132,30 @@ static NitriteBuilder builder() {
ObjectRepository getRepository(Class type, String key);
/**
- * Opens a type-safe object repository using a {@link EntityDecorator}. If the repository
- * does not exist it will be created automatically and returned. If a
- * repository is already opened, it is returned as is.
+ * Opens a type-safe object repository using a {@link EntityDecorator}. If the
+ * repository does not exist it will be created automatically and returned.
+ * If a repository is already opened, it is returned as is.
*
* The returned repository is thread-safe for concurrent use.
*
- * @param the type parameter
+ * @param the type parameter
* @param entityDecorator the entityDecorator
* @return the repository
*/
ObjectRepository getRepository(EntityDecorator entityDecorator);
/**
- * Opens a type-safe object repository using a {@link EntityDecorator} and a key identifier
- * from the store. If the repository does not exist it will be created automatically and
- * returned. If a repository is already opened, it is returned as is.
+ * Opens a type-safe object repository using a {@link EntityDecorator} and a key
+ * identifier from the store. If the repository does not exist it will be
+ * created
+ * automatically and returned. If a repository is already opened, it is returned
+ * as is.
*
* The returned repository is thread-safe for concurrent use.
*
- * @param the type parameter
+ * @param the type parameter
* @param entityDecorator the entityDecorator
- * @param key the key
+ * @param key the key
* @return the repository
*/
ObjectRepository getRepository(EntityDecorator entityDecorator, String key);
@@ -185,17 +202,17 @@ static NitriteBuilder builder() {
void destroyRepository(EntityDecorator type, String key);
/**
- * Gets the set of all {@link NitriteCollection}s' names saved in the store.
+ * Gets the set of all {@link NitriteCollection}s' names in the database.
*
- * @return the set of all collections' names.
+ * @return a set of all collection names in the database
*/
Set listCollectionNames();
/**
* Gets the set of all fully qualified class names corresponding
- * to all {@link ObjectRepository}s in the store.
+ * to all {@link ObjectRepository}s in the database.
*
- * @return the set of all registered classes' names.
+ * @return a set of all the repository names in the Nitrite database.
*/
Set listRepositories();
@@ -203,21 +220,22 @@ static NitriteBuilder builder() {
* Gets the map of all key to the fully qualified class names corresponding
* to all keyed-{@link ObjectRepository}s in the store.
*
- * @return the set of all registered classes' names.
+ * @return a map of all keyed-repositories keyed by their names
*/
Map> listKeyedRepositories();
/**
- * Checks whether the store has any unsaved changes.
+ * Checks if there are any unsaved changes in the Nitrite database.
*
- * @return true if there are unsaved changes; otherwise false.
+ * @return {@code true} if there are unsaved changes, {@code false} otherwise.
*/
boolean hasUnsavedChanges();
/**
- * Checks whether the store is closed.
+ * Checks if the Nitrite database instance is closed.
*
- * @return true if closed; otherwise false.
+ * @return {@code true} if the Nitrite database instance is closed;
+ * {@code false} otherwise.
*/
boolean isClosed();
@@ -229,16 +247,18 @@ static NitriteBuilder builder() {
NitriteConfig getConfig();
/**
- * Gets the {@link NitriteStore} instance powering the database.
+ * Returns the {@link NitriteStore} instance associated with this Nitrite
+ * database.
*
- * @return the {@link NitriteStore} instance of the database.
+ * @return the {@link NitriteStore} instance associated with this Nitrite
+ * database.
*/
NitriteStore> getStore();
/**
- * Gets database meta data.
+ * Returns the metadata of the database store.
*
- * @return the database meta data
+ * @return the metadata of the database store.
*/
StoreMetaData getDatabaseMetaData();
@@ -247,18 +267,25 @@ static NitriteBuilder builder() {
*
* @return the session
*/
+ /**
+ * Creates a new session for the Nitrite database. A session is a lightweight
+ * container that holds transactions. Multiple sessions can be created for a
+ * single Nitrite database instance.
+ *
+ * @return a new session for the Nitrite database.
+ */
Session createSession();
/**
* Closes the database.
- * */
+ */
void close();
/**
- * Checks whether a particular {@link NitriteCollection} exists in the store.
+ * Checks if a collection with the given name exists in the database.
*
- * @param name the name of the collection.
- * @return true if the collection exists; otherwise false.
+ * @param name the name of the collection to check
+ * @return true if a collection with the given name exists, false otherwise
*/
default boolean hasCollection(String name) {
checkOpened();
@@ -266,11 +293,11 @@ default boolean hasCollection(String name) {
}
/**
- * Checks whether a particular {@link ObjectRepository} exists in the store.
+ * Checks if a repository of the specified type exists in the database.
*
- * @param the type parameter
- * @param type the type of the object
- * @return true if the repository exists; otherwise false.
+ * @param type the type of the repository to check for
+ * @param the type of the repository
+ * @return true if a repository of the specified type exists, false otherwise
*/
default boolean hasRepository(Class type) {
checkOpened();
@@ -279,26 +306,29 @@ default boolean hasRepository(Class type) {
}
/**
- * Checks whether a particular keyed-{@link ObjectRepository} exists in the store.
+ * Checks if a repository of the specified type and the given key exists in
+ * the database.
*
- * @param the type parameter.
- * @param type the type of the object.
- * @param key the key, which will be appended to the repositories name.
- * @return true if the repository exists; otherwise false.
+ * @param type the entity type of the repository
+ * @param key the key of the repository
+ * @param the type of the entity
+ * @return true if a repository with the given key exists for the specified
+ * entity type; false otherwise
*/
default boolean hasRepository(Class type, String key) {
checkOpened();
String entityName = ObjectUtils.getEntityName(type);
return listKeyedRepositories().containsKey(key)
- && listKeyedRepositories().get(key).contains(entityName);
+ && listKeyedRepositories().get(key).contains(entityName);
}
/**
- * Checks whether a particular {@link ObjectRepository} exists in the store.
+ * Checks if a repository of the specified type described by the
+ * {@link EntityDecorator} exists in the database.
*
- * @param the type parameter
+ * @param the type parameter
* @param entityDecorator entityDecorator
- * @return true if the repository exists; otherwise false.
+ * @return true if the repository exists; false otherwise.
*/
default boolean hasRepository(EntityDecorator entityDecorator) {
checkOpened();
@@ -307,23 +337,27 @@ default boolean hasRepository(EntityDecorator entityDecorator) {
}
/**
- * Checks whether a particular keyed-{@link ObjectRepository} exists in the store.
+ * Checks if a keyed-repository of the specified type described by the
+ * {@link EntityDecorator} exists in the database.
*
- * @param the type parameter.
+ * @param the type parameter.
* @param entityDecorator entityDecorator.
- * @param key the key, which will be appended to the repositories name.
- * @return true if the repository exists; otherwise false.
+ * @param key the key, which will be appended to the repositories
+ * name.
+ * @return true if the repository exists; false otherwise.
*/
default boolean hasRepository(EntityDecorator entityDecorator, String key) {
checkOpened();
return listKeyedRepositories().containsKey(key)
- && listKeyedRepositories().get(key).contains(entityDecorator.getEntityName());
+ && listKeyedRepositories().get(key).contains(entityDecorator.getEntityName());
}
/**
- * Validate the collection name.
+ * Validates the given collection name.
*
- * @param name the name
+ * @param name the name of the collection to validate
+ * @throws ValidationException if the name is null, empty, or contains any
+ * reserved names
*/
default void validateCollectionName(String name) {
notNull(name, "name cannot be null");
@@ -337,7 +371,8 @@ default void validateCollectionName(String name) {
}
/**
- * Checks if the store is opened.
+ * Checks if the Nitrite database is opened or not. Throws a
+ * {@link NitriteIOException} if the database is closed.
*/
default void checkOpened() {
if (getStore() == null || getStore().isClosed()) {
diff --git a/nitrite/src/main/java/org/dizitart/no2/NitriteBuilder.java b/nitrite/src/main/java/org/dizitart/no2/NitriteBuilder.java
index 8aafb1913..48b938264 100644
--- a/nitrite/src/main/java/org/dizitart/no2/NitriteBuilder.java
+++ b/nitrite/src/main/java/org/dizitart/no2/NitriteBuilder.java
@@ -17,22 +17,24 @@
package org.dizitart.no2;
import lombok.Getter;
-import lombok.extern.slf4j.Slf4j;
import org.dizitart.no2.common.concurrent.ThreadPoolManager;
import org.dizitart.no2.exceptions.NitriteSecurityException;
import org.dizitart.no2.migration.Migration;
import org.dizitart.no2.common.module.NitriteModule;
/**
- * A builder utility to create a {@link Nitrite} database instance.
- *
+ * The NitriteBuilder class provides a fluent API to configure and create a
+ * Nitrite database instance.
+ *
* @author Anindya Chatterjee
* @see Nitrite
* @since 1.0
*/
-@Slf4j
public class NitriteBuilder {
@Getter
+ /**
+ * The Nitrite configuration object.
+ */
private final NitriteConfig nitriteConfig;
/**
@@ -43,11 +45,15 @@ public class NitriteBuilder {
}
/**
- * Sets the embedded field separator character. Default value
- * is `.`
+ * Sets the field separator character for Nitrite. It is used to separate field
+ * names in a nested document. For example, if a document has a field
+ * address which is a nested document, then the field street
+ * of the nested document can be accessed using address.street syntax.
+ *
+ * The default value is [. ].
*
- * @param separator the separator
- * @return the {@link NitriteBuilder} instance.
+ * @param separator the field separator character to use
+ * @return the NitriteBuilder instance
*/
public NitriteBuilder fieldSeparator(String separator) {
this.nitriteConfig.fieldSeparator(separator);
@@ -55,10 +61,11 @@ public NitriteBuilder fieldSeparator(String separator) {
}
/**
- * Loads {@link NitriteModule} instance.
+ * Loads a Nitrite module into the Nitrite database. The module can be used to
+ * extend the functionality of Nitrite.
*
- * @param module the {@link NitriteModule} instance.
- * @return the {@link NitriteBuilder} instance.
+ * @param module the {@link NitriteModule} to be loaded
+ * @return the {@link NitriteBuilder} instance
*/
public NitriteBuilder loadModule(NitriteModule module) {
this.nitriteConfig.loadModule(module);
@@ -66,10 +73,11 @@ public NitriteBuilder loadModule(NitriteModule module) {
}
/**
- * Adds instructions to perform during schema migration.
+ * Adds one or more migrations to the Nitrite database. Migrations are used to
+ * upgrade the database schema when the application version changes.
*
- * @param migrations the migrations
- * @return the nitrite builder
+ * @param migrations one or more migrations to add to the Nitrite database.
+ * @return the NitriteBuilder instance.
*/
public NitriteBuilder addMigrations(Migration... migrations) {
for (Migration migration : migrations) {
@@ -79,10 +87,10 @@ public NitriteBuilder addMigrations(Migration... migrations) {
}
/**
- * Sets the current schema version.
+ * Sets the schema version for the Nitrite database.
*
- * @param version the version
- * @return the nitrite builder
+ * @param version the schema version to set
+ * @return the NitriteBuilder instance
*/
public NitriteBuilder schemaVersion(Integer version) {
this.nitriteConfig.currentSchemaVersion(version);
@@ -90,15 +98,21 @@ public NitriteBuilder schemaVersion(Integer version) {
}
/**
- * Opens or creates a new nitrite database. If it is an in-memory store,
- * then it will create a new one. If it is a file based store, and if the file does not
- * exist, then it will create a new file store and open; otherwise it will
- * open the existing file store.
+ * Opens or creates a new Nitrite database. If it is configured as in-memory
+ * database, then it will create a new database everytime. If it is configured
+ * as a file based database, and if the file does not exist, then it will create
+ * a new file store and open the database; otherwise it will open the existing
+ * database file.
*
* @return the nitrite database instance.
- * @throws org.dizitart.no2.exceptions.NitriteIOException if unable to create a new in-memory database.
- * @throws org.dizitart.no2.exceptions.NitriteIOException if the database is corrupt and recovery fails.
- * @throws IllegalArgumentException if the directory does not exist.
+ * @throws org.dizitart.no2.exceptions.NitriteIOException if unable to create a
+ * new in-memory
+ * database.
+ * @throws org.dizitart.no2.exceptions.NitriteIOException if the database is
+ * corrupt and recovery
+ * fails.
+ * @throws IllegalArgumentException if the directory does
+ * not exist.
*/
public Nitrite openOrCreate() {
this.nitriteConfig.autoConfigure();
@@ -109,23 +123,30 @@ public Nitrite openOrCreate() {
}
/**
- * Opens or creates a new nitrite database. If it is an in-memory store,
- * then it will create a new one. If it is a file based store, and if the file does not
- * exist, then it will create a new file store and open; otherwise it will
- * open the existing file store.
+ * Opens or creates a new Nitrite database with the given username and password.
+ * If it is configured as in-memory database, then it will create a new database
+ * everytime. If it is configured as a file based database, and if the file
+ * does not exist, then it will create a new file store and open the database;
+ * otherwise it will open the existing database file.
+ *
*
- * While creating a new database, it will use the specified user credentials.
- * While opening an existing database, it will use the specified credentials
- * to open it.
- *
+ * NOTE: Both username and password must be provided or both must be null.
*
* @param username the username
* @param password the password
* @return the nitrite database instance.
- * @throws NitriteSecurityException if the user credentials are wrong or one of them is empty string.
- * @throws org.dizitart.no2.exceptions.NitriteIOException if unable to create a new in-memory database.
- * @throws org.dizitart.no2.exceptions.NitriteIOException if the database is corrupt and recovery fails.
- * @throws org.dizitart.no2.exceptions.NitriteIOException if the directory does not exist.
+ * @throws NitriteSecurityException if the user
+ * credentials are wrong
+ * or one of them is
+ * empty string.
+ * @throws org.dizitart.no2.exceptions.NitriteIOException if unable to create a
+ * new in-memory
+ * database.
+ * @throws org.dizitart.no2.exceptions.NitriteIOException if the database is
+ * corrupt and recovery
+ * fails.
+ * @throws org.dizitart.no2.exceptions.NitriteIOException if the directory does
+ * not exist.
*/
public Nitrite openOrCreate(String username, String password) {
this.nitriteConfig.autoConfigure();
diff --git a/nitrite/src/main/java/org/dizitart/no2/NitriteConfig.java b/nitrite/src/main/java/org/dizitart/no2/NitriteConfig.java
index 77ed5bfca..ca200a000 100644
--- a/nitrite/src/main/java/org/dizitart/no2/NitriteConfig.java
+++ b/nitrite/src/main/java/org/dizitart/no2/NitriteConfig.java
@@ -36,12 +36,12 @@
import java.util.TreeMap;
/**
- * A class to configure {@link Nitrite} database.
- *
+ * NitriteConfig is a configuration class for Nitrite database.
+ *
* @author Anindya Chatterjee.
- * @since 4.0.0
+ * @since 4.0
*/
-@Slf4j
+@Slf4j(topic = "nitrite")
@ToString
public class NitriteConfig implements AutoCloseable {
/**
@@ -56,12 +56,22 @@ public class NitriteConfig implements AutoCloseable {
protected final PluginManager pluginManager;
@Getter
+ /**
+ * The separator used to separate field names in a nested field.
+ */
private static String fieldSeparator = ".";
@Getter
+ /**
+ * A map of migrations to be applied to the database.
+ */
private final Map> migrations;
@Getter
+ /**
+ * The schema version of the Nitrite database. Defaults to
+ * {@link Constants#INITIAL_SCHEMA_VERSION}.
+ */
private Integer schemaVersion = Constants.INITIAL_SCHEMA_VERSION;
/**
@@ -73,55 +83,57 @@ public NitriteConfig() {
}
/**
- * Sets the embedded field separator character. Default value
- * is `.`
+ * Sets the field separator for Nitrite database.
*
- * @param separator the separator
+ * @param separator the field separator to be set.
+ * @throws InvalidOperationException if the separator is attempted to be changed
+ * after database initialization.
*/
public void fieldSeparator(String separator) {
if (configured) {
throw new InvalidOperationException("Cannot change the separator after database" +
- " initialization");
+ " initialization");
}
NitriteConfig.fieldSeparator = separator;
}
/**
- * Loads {@link NitritePlugin} instances defined in the {@link NitriteModule}.
+ * Loads {@link NitritePlugin} instances defined in the {@link NitriteModule}
+ * into the configuration.
*
- * @param module the {@link NitriteModule} instances.
- * @return the {@link NitriteConfig} instance.
+ * @param module the Nitrite module to be loaded
+ * @return the Nitrite configuration instance
+ * @throws InvalidOperationException if the database is already initialized
*/
public NitriteConfig loadModule(NitriteModule module) {
if (configured) {
throw new InvalidOperationException("Cannot load module after database" +
- " initialization");
+ " initialization");
}
pluginManager.loadModule(module);
return this;
}
/**
- * Adds schema migration instructions.
+ * Adds a migration step to the configuration. A migration step is a process of
+ * updating the database from one version to another. If the database is already
+ * initialized, then migration steps cannot be added.
*
- * @param migration the migration
- * @return the nitrite config
+ * @param migration the migration step to be added.
+ * @return the NitriteConfig instance.
+ * @throws InvalidOperationException if migration steps are added after database
+ * initialization.
*/
- @SuppressWarnings("Java8MapApi")
public NitriteConfig addMigration(Migration migration) {
if (configured) {
throw new InvalidOperationException("Cannot add migration steps after database" +
- " initialization");
+ " initialization");
}
if (migration != null) {
final int start = migration.getFromVersion();
final int end = migration.getToVersion();
- TreeMap targetMap = migrations.get(start);
- if (targetMap == null) {
- targetMap = new TreeMap<>();
- migrations.put(start, targetMap);
- }
+ TreeMap targetMap = migrations.computeIfAbsent(start, k -> new TreeMap<>());
Migration existing = targetMap.get(end);
if (existing != null) {
log.warn("Overriding migration " + existing + " with " + migration);
@@ -132,37 +144,42 @@ public NitriteConfig addMigration(Migration migration) {
}
/**
- * Sets the current schema version.
+ * Sets the current schema version of the Nitrite database.
*
- * @param version the version
- * @return the nitrite config
+ * @param version the current schema version.
+ * @return the NitriteConfig instance.
+ * @throws InvalidOperationException if the schema version is attempted to be
+ * added after database initialization.
*/
public NitriteConfig currentSchemaVersion(Integer version) {
if (configured) {
throw new InvalidOperationException("Cannot add schema version info after database" +
- " initialization");
+ " initialization");
}
this.schemaVersion = version;
return this;
}
/**
- * Autoconfigures nitrite database with default configuration values and
- * default built-in plugins.
+ * Automatically configures Nitrite database by finding and loading plugins.
+ *
+ * @throws InvalidOperationException if autoconfigure is executed after database
+ * initialization.
*/
public void autoConfigure() {
if (configured) {
throw new InvalidOperationException("Cannot execute autoconfigure after database" +
- " initialization");
+ " initialization");
}
pluginManager.findAndLoadPlugins();
}
/**
- * Finds a {@link NitriteIndexer} by indexType.
+ * Finds the {@link NitriteIndexer} for the given index type.
*
- * @param indexType the type of {@link NitriteIndexer} to find.
- * @return the {@link NitriteIndexer}
+ * @param indexType the type of the index to find
+ * @return the {@link NitriteIndexer} for the given index type
+ * @throws IndexingException if no indexer is found for the given index type
*/
public NitriteIndexer findIndexer(String indexType) {
NitriteIndexer nitriteIndexer = pluginManager.getIndexerMap().get(indexType);
@@ -175,23 +192,27 @@ public NitriteIndexer findIndexer(String indexType) {
}
/**
- * Gets the {@link NitriteMapper} instance.
+ * Returns the {@link NitriteMapper} instance used by Nitrite.
*
- * @return the {@link NitriteMapper}
+ * @return the NitriteMapper instance used by Nitrite.
*/
public NitriteMapper nitriteMapper() {
return pluginManager.getNitriteMapper();
}
/**
- * Gets {@link NitriteStore} instance.
+ * Returns the {@link NitriteStore} associated with this instance.
*
- * @return the {@link NitriteStore}
+ * @return the {@link NitriteStore} associated with this instance.
*/
public NitriteStore> getNitriteStore() {
return pluginManager.getNitriteStore();
}
+ /**
+ * Closes the NitriteConfig instance and releases any resources
+ * associated with it.
+ */
@Override
public void close() {
if (pluginManager != null) {
diff --git a/nitrite/src/main/java/org/dizitart/no2/NitriteDatabase.java b/nitrite/src/main/java/org/dizitart/no2/NitriteDatabase.java
index e0f6acfdb..602b40195 100644
--- a/nitrite/src/main/java/org/dizitart/no2/NitriteDatabase.java
+++ b/nitrite/src/main/java/org/dizitart/no2/NitriteDatabase.java
@@ -47,7 +47,7 @@
* @author Anindya Chatterjee.
* @since 4.0
*/
-@Slf4j
+@Slf4j(topic = "nitrite")
class NitriteDatabase implements Nitrite {
private final CollectionFactory collectionFactory;
private final RepositoryFactory repositoryFactory;
diff --git a/nitrite/src/main/java/org/dizitart/no2/collection/CollectionFactory.java b/nitrite/src/main/java/org/dizitart/no2/collection/CollectionFactory.java
index ea2973230..a4088a967 100644
--- a/nitrite/src/main/java/org/dizitart/no2/collection/CollectionFactory.java
+++ b/nitrite/src/main/java/org/dizitart/no2/collection/CollectionFactory.java
@@ -33,9 +33,8 @@
import static org.dizitart.no2.common.util.ValidationUtils.notNull;
/**
- * A factory class to create {@link NitriteCollection}.
- * NOTE: Internal API
* @author Anindya Chatterjee
+ * @since 4.0
*/
public class CollectionFactory {
private final Map collectionMap;
diff --git a/nitrite/src/main/java/org/dizitart/no2/collection/DefaultNitriteCollection.java b/nitrite/src/main/java/org/dizitart/no2/collection/DefaultNitriteCollection.java
index aedb15e49..df07fe291 100644
--- a/nitrite/src/main/java/org/dizitart/no2/collection/DefaultNitriteCollection.java
+++ b/nitrite/src/main/java/org/dizitart/no2/collection/DefaultNitriteCollection.java
@@ -49,6 +49,7 @@
/**
* @author Anindya Chatterjee.
+ * @since 1.0
*/
class DefaultNitriteCollection implements NitriteCollection {
private final String collectionName;
diff --git a/nitrite/src/main/java/org/dizitart/no2/collection/Document.java b/nitrite/src/main/java/org/dizitart/no2/collection/Document.java
index 9b47640c3..bf52fbec2 100644
--- a/nitrite/src/main/java/org/dizitart/no2/collection/Document.java
+++ b/nitrite/src/main/java/org/dizitart/no2/collection/Document.java
@@ -16,6 +16,7 @@
package org.dizitart.no2.collection;
+import org.dizitart.no2.NitriteConfig;
import org.dizitart.no2.common.tuples.Pair;
import java.io.Serializable;
@@ -26,7 +27,27 @@
import static org.dizitart.no2.common.Constants.*;
/**
- * A representation of a nitrite document.
+ * Represents a document in Nitrite database.
+ *
+ * Nitrite document are composed of key-value pairs. A key is always a {@link String} and value
+ * can be anything including null.
+ *
+ * Nitrite document supports nested documents as well. The key of a nested document is a {@link String}
+ * separated by {@link NitriteConfig#getFieldSeparator()}. By default, Nitrite uses `.` as field separator.
+ * This can be changed by setting {@link NitriteConfig#fieldSeparator(String)}.
+ *
+ * For example, if a document has a nested document
+ * { "a" : { "b" : 1 } }, then the value of inside the nested document can be retrieved by
+ * calling {@link #get(String)} with key a.b.
+ *
+ * Below fields are reserved and cannot be used as key in a document.
+ *
+ * _id : The unique identifier of the document. If not provided,
+ * Nitrite will generate a unique {@link NitriteId} for the document during insertion.
+ * _revision : The revision number of the document.
+ * _source : The source of the document.
+ * _modified : The last modified time of the document in milliseconds since epoch.
+ *
*
* @since 1.0
* @author Anindya Chatterjee
@@ -34,7 +55,7 @@
public interface Document extends Iterable>, Cloneable, Serializable {
/**
- * Creates a new empty document.
+ * Creates an empty document.
*
* @return the document
*/
diff --git a/nitrite/src/main/java/org/dizitart/no2/collection/DocumentCursor.java b/nitrite/src/main/java/org/dizitart/no2/collection/DocumentCursor.java
index ab87832ea..b2bfc01e8 100644
--- a/nitrite/src/main/java/org/dizitart/no2/collection/DocumentCursor.java
+++ b/nitrite/src/main/java/org/dizitart/no2/collection/DocumentCursor.java
@@ -20,26 +20,16 @@
import org.dizitart.no2.common.RecordStream;
/**
- * An interface to iterate over {@link NitriteCollection#find()} results. It provides a
- * mechanism to iterate over all {@link NitriteId}s of the result.
+ * The DocumentCursor represents a cursor as a stream of {@link Document} to iterate over {@link NitriteCollection#find()} results.
+ * It also provides methods for projection and perform left outer join with other DocumentCursor.
+ *
*
* {@code
- *
- * // create/open a database
- * Nitrite db = Nitrite.builder()
- * .openOrCreate("user", "password");
- *
- * // create a collection named - test
- * NitriteCollection collection = db.getCollection("test");
- *
- * // returns all ids un-filtered
* DocumentCursor result = collection.find();
*
* for (Document doc : result) {
* // use your logic with the retrieved doc here
* }
- *
- * }*
*
*
* @author Anindya Chatterjee
diff --git a/nitrite/src/main/java/org/dizitart/no2/collection/FindOptions.java b/nitrite/src/main/java/org/dizitart/no2/collection/FindOptions.java
index 45469e068..b801ac3d3 100644
--- a/nitrite/src/main/java/org/dizitart/no2/collection/FindOptions.java
+++ b/nitrite/src/main/java/org/dizitart/no2/collection/FindOptions.java
@@ -36,16 +36,28 @@
@Accessors(fluent = true, chain = true)
@Setter(AccessLevel.PACKAGE)
public class FindOptions {
+ /**
+ * Gets the {@link SortableFields} for sorting the find results.
+ * */
private SortableFields orderBy;
+
+ /**
+ * Gets the skip count.
+ * */
private Long skip;
+
+ /**
+ * Gets the limit count.
+ * */
private Long limit;
+
+ /**
+ * Indicates if the find operation should return distinct results.
+ * */
private boolean distinct = false;
/**
* Specifies the {@link Collator}.
- *
- * @param collator the collator
- * @return the collator.
*/
@Setter(AccessLevel.PUBLIC)
private Collator collator;
diff --git a/nitrite/src/main/java/org/dizitart/no2/collection/FindPlan.java b/nitrite/src/main/java/org/dizitart/no2/collection/FindPlan.java
index a2f86a27d..b34a28a81 100644
--- a/nitrite/src/main/java/org/dizitart/no2/collection/FindPlan.java
+++ b/nitrite/src/main/java/org/dizitart/no2/collection/FindPlan.java
@@ -31,27 +31,66 @@
import java.util.Map;
/**
- * Represents an execution plan of a find operation after optimization.
+ * A plan for finding documents in a collection.
*
* @author Anindya Chatterjee
- * @since 4.0.0
+ * @since 4.0
*/
@Data
public class FindPlan {
+ /**
+ * Gets the {@link FieldBasedFilter} for byId search if any.
+ * */
private FieldBasedFilter byIdFilter;
+
+ /**
+ * Gets the {@link IndexScanFilter} for index scan if any.
+ * */
private IndexScanFilter indexScanFilter;
+
+ /**
+ * Gets the {@link Filter} for collection scan if any.
+ * */
private Filter collectionScanFilter;
+ /**
+ * Gets the {@link IndexDescriptor} for index scan if any.
+ * */
private IndexDescriptor indexDescriptor;
+
+ /**
+ * Gets the index scan order.
+ * */
private Map indexScanOrder;
+
+ /**
+ * Gets the blocking sort order.
+ * */
private List> blockingSortOrder;
+ /**
+ * Gets the skip count.
+ * */
private Long skip;
+
+ /**
+ * Gets the limit count.
+ * */
private Long limit;
+
+ /**
+ * Gets the distinct flag.
+ * */
private boolean distinct;
+ /**
+ * Gets the {@link Collator}.
+ * */
private Collator collator;
+ /**
+ * Gets the sub plans.
+ * */
private List subPlans;
/**
diff --git a/nitrite/src/main/java/org/dizitart/no2/collection/NitriteCollection.java b/nitrite/src/main/java/org/dizitart/no2/collection/NitriteCollection.java
index 01a721198..1f6cdbdaf 100644
--- a/nitrite/src/main/java/org/dizitart/no2/collection/NitriteCollection.java
+++ b/nitrite/src/main/java/org/dizitart/no2/collection/NitriteCollection.java
@@ -35,12 +35,13 @@
import static org.dizitart.no2.common.util.ValidationUtils.notNull;
/**
- * Represents a named document collection stored in nitrite database.
+ * Represents a named document collection stored in Nitrite database.
* It persists documents into the database. Each document is associated
* with a unique {@link NitriteId} in a collection.
*
* A nitrite collection supports indexing. Every nitrite collection is also
- * observable.
+ * observable. It means, any change in a collection can be listened back via
+ * registering a {@link CollectionEventListener}.
*
* Create a collection
*
diff --git a/nitrite/src/main/java/org/dizitart/no2/collection/NitriteDocument.java b/nitrite/src/main/java/org/dizitart/no2/collection/NitriteDocument.java
index 84e51e43d..314d08619 100644
--- a/nitrite/src/main/java/org/dizitart/no2/collection/NitriteDocument.java
+++ b/nitrite/src/main/java/org/dizitart/no2/collection/NitriteDocument.java
@@ -38,7 +38,6 @@
import static org.dizitart.no2.common.util.ValidationUtils.notNull;
/**
- * A default implementation of nitrite document.
*
* @since 4.0
* @author Anindya Chatterjee
@@ -169,7 +168,26 @@ public Document clone() {
@Override
public Document merge(Document document) {
if (document instanceof NitriteDocument) {
- super.putAll((NitriteDocument) document);
+ NitriteDocument nitriteDocument = (NitriteDocument) document;
+ for (Pair entry : nitriteDocument) {
+ String key = entry.getFirst();
+ Object value = entry.getSecond();
+ if (value instanceof NitriteDocument) {
+ // if the value is a document, merge it recursively
+ if (containsKey(key)) {
+ // if the current document already contains the key,
+ // then merge the embedded document
+ get(key, Document.class).merge((Document) value);
+ } else {
+ // if the current document does not contain the key,
+ // then put the embedded document as it is
+ put(key, value);
+ }
+ } else {
+ // if there is no more embedded document, put the field in the document
+ put(key, value);
+ }
+ }
} else {
throw new InvalidOperationException("Document merge only supports NitriteDocument");
}
diff --git a/nitrite/src/main/java/org/dizitart/no2/collection/NitriteId.java b/nitrite/src/main/java/org/dizitart/no2/collection/NitriteId.java
index 302053861..ad9869f3b 100644
--- a/nitrite/src/main/java/org/dizitart/no2/collection/NitriteId.java
+++ b/nitrite/src/main/java/org/dizitart/no2/collection/NitriteId.java
@@ -17,6 +17,7 @@
package org.dizitart.no2.collection;
import lombok.EqualsAndHashCode;
+import lombok.Getter;
import org.dizitart.no2.exceptions.InvalidIdException;
import java.io.IOException;
@@ -33,18 +34,24 @@
*
* During insertion if a unique object is supplied in the '_id' field
* of the document, then the value of the '_id' field will be used to
- * create a new {@link NitriteId}. If that is not supplied, then nitrite
- * will auto generate one and supply it in the '_id' field of the document.
+ * create a new {@link NitriteId}. If the '_id' field is not supplied, then
+ * nitrite will generate a new [NitriteId] and will add it to the document.
*
* @author Anindya Chatterjee
* @see NitriteCollection#getById(NitriteId)
* @since 1.0
*/
+@Getter
@EqualsAndHashCode
public final class NitriteId implements Comparable, Serializable {
private static final long serialVersionUID = 1477462375L;
private static final SnowflakeIdGenerator generator = new SnowflakeIdGenerator();
+ /**
+ * Gets the underlying value of the NitriteId.
+ *
+ * The value is a string representation of a 64bit integer number.
+ */
private String idValue;
private NitriteId() {
@@ -56,7 +63,7 @@ private NitriteId(String value) {
}
/**
- * Gets a new auto-generated {@link NitriteId}.
+ * Creates a new auto-generated {@link NitriteId}.
*
* @return a new auto-generated {@link NitriteId}.
*/
@@ -65,7 +72,9 @@ public static NitriteId newId() {
}
/**
- * Creates a {@link NitriteId} from a long value.
+ * Creates a {@link NitriteId} from a value.
+ *
+ * The value must be a string representation of a 64bit integer number.
*
* @param value the value
* @return the {@link NitriteId}
@@ -75,6 +84,14 @@ public static NitriteId createId(String value) {
return new NitriteId(value);
}
+ /**
+ * Validates a value to be used as {@link NitriteId}.
+ *
+ * The value must be a string representation of a 64bit integer number.
+ *
+ * @param value the value
+ * @return `true` if the value is valid; otherwise `false`.
+ * */
public static boolean validId(Object value) {
if (value == null) {
throw new InvalidIdException("id cannot be null");
@@ -104,15 +121,6 @@ public String toString() {
return "";
}
- /**
- * Gets the underlying id object.
- *
- * @return the underlying id object.
- */
- public String getIdValue() {
- return idValue;
- }
-
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.writeUTF(idValue);
}
diff --git a/nitrite/src/main/java/org/dizitart/no2/collection/SnowflakeIdGenerator.java b/nitrite/src/main/java/org/dizitart/no2/collection/SnowflakeIdGenerator.java
index a7b56663c..b4a7e25e7 100644
--- a/nitrite/src/main/java/org/dizitart/no2/collection/SnowflakeIdGenerator.java
+++ b/nitrite/src/main/java/org/dizitart/no2/collection/SnowflakeIdGenerator.java
@@ -24,8 +24,8 @@
import java.util.UUID;
/**
- * Generate unique IDs using the Twitter Snowflake algorithm (see https://github.com/twitter/snowflake). Snowflake IDs
- * are 64 bit positive longs composed of:
+ * Generate unique IDs using the Twitter Snowflake algorithm (see Snowflake ).
+ * Snowflake IDs are 64 bit positive longs composed of:
*
*
* 41 bits time stamp
@@ -34,24 +34,23 @@
* 1 unused sign bit, always set to 0
*
*
- * This is a derivative work of - https://github.com/apache/marmotta/blob/master/libraries/kiwi/kiwi-triplestore/src/main/java/org/apache/marmotta/kiwi/generator/SnowflakeIDGenerator.java
+ * This is a derivative work of -
+ * Sebastian Schaffert
*
*
* @author Sebastian Schaffert (sschaffert@apache.org)
* @since 4.0
*/
-@Slf4j
+@Slf4j(topic = "nitrite")
public class SnowflakeIdGenerator {
private final SecureRandom random;
private final long nodeIdBits = 10L;
private long nodeId;
-
private volatile long lastTimestamp = -1L;
private volatile long sequence = 0L;
private static final long no2epoch = 1288834974657L;
-
public SnowflakeIdGenerator() {
random = new SecureRandom();
long maxNodeId = ~(-1L << nodeIdBits);
@@ -79,7 +78,6 @@ protected long getNodeId() {
return ((0x000000FF & (long) uuid[uuid.length - 1]) | (0x0000FF00 & (((long) rndByte) << 8))) >> 6;
}
-
/**
* Return the next unique id for the type with the given name using the generator's id generation strategy.
*
diff --git a/nitrite/src/main/java/org/dizitart/no2/collection/UpdateOptions.java b/nitrite/src/main/java/org/dizitart/no2/collection/UpdateOptions.java
index 54cba94b5..73319e67c 100644
--- a/nitrite/src/main/java/org/dizitart/no2/collection/UpdateOptions.java
+++ b/nitrite/src/main/java/org/dizitart/no2/collection/UpdateOptions.java
@@ -23,12 +23,13 @@
import org.dizitart.no2.filters.Filter;
/**
- * Settings to control update operation in {@link NitriteCollection}.
+ * Represents options to configure update operation.
*
* @author Anindya Chatterjee
* @see NitriteCollection#update(Filter, Document, UpdateOptions)
* @since 1.0
*/
+@Getter
@ToString
@EqualsAndHashCode
public class UpdateOptions {
@@ -37,20 +38,13 @@ public class UpdateOptions {
* Indicates if the update operation will insert a new document if it
* does not find any existing document to update.
*
- * @param insertIfAbsent a value indicating, if a new document to insert in case the
- * filter fails to find a document to update.
- * @return `true` if a new document to insert; otherwise, `false`.
* @see NitriteCollection#update(Filter, Document, UpdateOptions)
*/
- @Getter
@Setter
private boolean insertIfAbsent;
/**
* Indicates if only one document will be updated or all of them.
- *
- * @param justOnce a value indicating if only one document to update or all.
- * @return `true` if only one document to update; otherwise, `false`.
*/
@Getter
@Setter
diff --git a/nitrite/src/main/java/org/dizitart/no2/collection/events/CollectionEventInfo.java b/nitrite/src/main/java/org/dizitart/no2/collection/events/CollectionEventInfo.java
index ccf350eff..28954a2b1 100644
--- a/nitrite/src/main/java/org/dizitart/no2/collection/events/CollectionEventInfo.java
+++ b/nitrite/src/main/java/org/dizitart/no2/collection/events/CollectionEventInfo.java
@@ -59,7 +59,7 @@ public class CollectionEventInfo {
*
* @param originator name of originator of the event.
* @return name of the originator.
- * @since 4.0.0
+ * @since 4.0
*/
private String originator;
diff --git a/nitrite/src/main/java/org/dizitart/no2/collection/events/CollectionEventListener.java b/nitrite/src/main/java/org/dizitart/no2/collection/events/CollectionEventListener.java
index 290f1493f..ea62dcfe0 100644
--- a/nitrite/src/main/java/org/dizitart/no2/collection/events/CollectionEventListener.java
+++ b/nitrite/src/main/java/org/dizitart/no2/collection/events/CollectionEventListener.java
@@ -20,9 +20,8 @@
import org.dizitart.no2.repository.ObjectRepository;
/**
- * An interface when implemented makes an object be
- * able to listen to any changes in a {@link NitriteCollection}
- * or {@link ObjectRepository}.
+ * A listener which is able to listen to any changes in a
+ * in a {@link NitriteCollection} or {@link ObjectRepository}.
*
* @author Anindya Chatterjee.
* @since 4.0
diff --git a/nitrite/src/main/java/org/dizitart/no2/collection/events/EventAware.java b/nitrite/src/main/java/org/dizitart/no2/collection/events/EventAware.java
index af2faa92b..4dbe3db52 100644
--- a/nitrite/src/main/java/org/dizitart/no2/collection/events/EventAware.java
+++ b/nitrite/src/main/java/org/dizitart/no2/collection/events/EventAware.java
@@ -17,26 +17,10 @@
package org.dizitart.no2.collection.events;
/**
- * Interface to be implemented by collections that wish to be aware
- * of any event.
- *
- * @author Anindya Chatterjee.
- * @see EventType
* @since 4.0
+ * @author Anindya Chatterjee
*/
public interface EventAware {
- /**
- * Subscribes an {@link CollectionEventListener} instance to listen to any
- * collection events.
- *
- * @param listener the listener
- */
void subscribe(CollectionEventListener listener);
-
- /**
- * Unsubscribes an {@link CollectionEventListener} instance.
- *
- * @param listener the listener.
- */
void unsubscribe(CollectionEventListener listener);
}
diff --git a/nitrite/src/main/java/org/dizitart/no2/collection/operation/CollectionOperations.java b/nitrite/src/main/java/org/dizitart/no2/collection/operation/CollectionOperations.java
index f0f6cb85f..fb57aa927 100644
--- a/nitrite/src/main/java/org/dizitart/no2/collection/operation/CollectionOperations.java
+++ b/nitrite/src/main/java/org/dizitart/no2/collection/operation/CollectionOperations.java
@@ -34,8 +34,6 @@
import java.util.Collection;
/**
- * The collection operations.
- *
* @author Anindya Chatterjee
* @since 1.0
*/
@@ -49,14 +47,6 @@ public class CollectionOperations implements AutoCloseable {
private WriteOperations writeOperations;
private ReadOperations readOperations;
- /**
- * Instantiates a new Collection operations.
- *
- * @param collectionName the collection name
- * @param nitriteMap the nitrite map
- * @param nitriteConfig the nitrite config
- * @param eventBus the event bus
- */
public CollectionOperations(String collectionName,
NitriteMap nitriteMap,
NitriteConfig nitriteConfig,
@@ -68,184 +58,79 @@ public CollectionOperations(String collectionName,
initialize();
}
- /**
- * Adds a document processor.
- *
- * @param processor the processor
- */
public void addProcessor(Processor processor) {
processorChain.add(processor);
}
- /**
- * Creates index.
- *
- * @param fields the fields
- * @param indexType the index type
- */
public void createIndex(Fields fields, String indexType) {
indexOperations.createIndex(fields, indexType);
}
- /**
- * Finds index descriptor.
- *
- * @param fields the fields
- * @return the index descriptor
- */
public IndexDescriptor findIndex(Fields fields) {
return indexOperations.findIndexDescriptor(fields);
}
- /**
- * Rebuilds index.
- *
- * @param indexDescriptor the index descriptor
- */
public void rebuildIndex(IndexDescriptor indexDescriptor) {
indexOperations.buildIndex(indexDescriptor, true);
}
- /**
- * Lists all indexes.
- *
- * @return the collection
- */
public Collection listIndexes() {
return indexOperations.listIndexes();
}
- /**
- * Checks if an index exists on the fields.
- *
- * @param fields the fields
- * @return the boolean
- */
public boolean hasIndex(Fields fields) {
return indexOperations.hasIndexEntry(fields);
}
- /**
- * Checks if indexing is going on the fields.
- *
- * @param fields the fields
- * @return the boolean
- */
public boolean isIndexing(Fields fields) {
return indexOperations.isIndexing(fields);
}
- /**
- * Drops index.
- *
- * @param fields the fields
- */
public void dropIndex(Fields fields) {
indexOperations.dropIndex(fields);
}
- /**
- * Drops all indices.
- */
public void dropAllIndices() {
indexOperations.dropAllIndices();
}
- /**
- * Inserts documents to the collection.
- *
- * @param documents the documents
- * @return the write result
- */
public WriteResult insert(Document[] documents) {
return writeOperations.insert(documents);
}
- /**
- * Updates documents in the collection.
- *
- * @param filter the filter
- * @param update the update
- * @param updateOptions the update options
- * @return the write result
- */
public WriteResult update(Filter filter, Document update, UpdateOptions updateOptions) {
return writeOperations.update(filter, update, updateOptions);
}
- /**
- * Removes document from the collection.
- *
- * @param document the document
- * @return the write result
- */
public WriteResult remove(Document document) {
return writeOperations.remove(document);
}
- /**
- * Removes document from collection.
- *
- * @param filter the filter
- * @param justOnce the just once
- * @return the write result
- */
public WriteResult remove(Filter filter, boolean justOnce) {
return writeOperations.remove(filter, justOnce);
}
- /**
- * Finds documents using filter.
- *
- * @param filter the filter
- * @param findOptions the find options
- * @return the document cursor
- */
public DocumentCursor find(Filter filter, FindOptions findOptions) {
return readOperations.find(filter, findOptions);
}
- /**
- * Gets document by id.
- *
- * @param nitriteId the nitrite id
- * @return the by id
- */
public Document getById(NitriteId nitriteId) {
return readOperations.getById(nitriteId);
}
- /**
- * Drops the collection.
- */
public void dropCollection() {
indexOperations.dropAllIndices();
dropNitriteMap();
}
- /**
- * Gets the size of the collection.
- *
- * @return the size
- */
public long getSize() {
return nitriteMap.size();
}
- /**
- * Gets the additional attributes for the collection.
- *
- * @return the attributes
- */
public Attributes getAttributes() {
return nitriteMap != null ? nitriteMap.getAttributes() : null;
}
- /**
- * Sets additional attributes in the collection.
- *
- * @param attributes the attributes
- */
public void setAttributes(Attributes attributes) {
nitriteMap.setAttributes(attributes);
}
diff --git a/nitrite/src/main/java/org/dizitart/no2/collection/operation/DocumentIndexWriter.java b/nitrite/src/main/java/org/dizitart/no2/collection/operation/DocumentIndexWriter.java
index 85ec0ccc8..31fece0a9 100644
--- a/nitrite/src/main/java/org/dizitart/no2/collection/operation/DocumentIndexWriter.java
+++ b/nitrite/src/main/java/org/dizitart/no2/collection/operation/DocumentIndexWriter.java
@@ -27,7 +27,6 @@
import java.util.Collection;
/**
- *
* @since 4.0
* @author Anindya Chatterjee
*/
diff --git a/nitrite/src/main/java/org/dizitart/no2/collection/operation/FindOptimizer.java b/nitrite/src/main/java/org/dizitart/no2/collection/operation/FindOptimizer.java
index 43a44b11a..919d5d36d 100644
--- a/nitrite/src/main/java/org/dizitart/no2/collection/operation/FindOptimizer.java
+++ b/nitrite/src/main/java/org/dizitart/no2/collection/operation/FindOptimizer.java
@@ -32,9 +32,7 @@
import static org.dizitart.no2.filters.Filter.and;
import static org.dizitart.no2.filters.Filter.or;
-
/**
- *
* @since 4.0
* @author Anindya Chatterjee
*/
diff --git a/nitrite/src/main/java/org/dizitart/no2/collection/operation/IndexManager.java b/nitrite/src/main/java/org/dizitart/no2/collection/operation/IndexManager.java
index 96bee500b..b8d6fc8c2 100644
--- a/nitrite/src/main/java/org/dizitart/no2/collection/operation/IndexManager.java
+++ b/nitrite/src/main/java/org/dizitart/no2/collection/operation/IndexManager.java
@@ -32,10 +32,8 @@
import static org.dizitart.no2.common.util.IndexUtils.deriveIndexMetaMapName;
/**
- * Represents the index manager for a collection.
- *
- * @author Anindya Chatterjee
* @since 4.0
+ * @author Anindya Chatterjee
*/
public class IndexManager implements AutoCloseable {
private final NitriteConfig nitriteConfig;
@@ -44,12 +42,6 @@ public class IndexManager implements AutoCloseable {
private final NitriteMap indexMetaMap;
private Collection indexDescriptorCache;
- /**
- * Instantiates a new {@link IndexManager}.
- *
- * @param collectionName the collection name
- * @param nitriteConfig the nitrite config
- */
public IndexManager(String collectionName, NitriteConfig nitriteConfig) {
this.collectionName = collectionName;
this.nitriteConfig = nitriteConfig;
@@ -58,21 +50,10 @@ public IndexManager(String collectionName, NitriteConfig nitriteConfig) {
initialize();
}
- /**
- * Checks if an index descriptor already exists on the fields.
- *
- * @param fields the fields
- * @return the boolean
- */
public boolean hasIndexDescriptor(Fields fields) {
return !findMatchingIndexDescriptors(fields).isEmpty();
}
- /**
- * Gets all defined index descriptors for the collection.
- *
- * @return the index descriptors
- */
public Collection getIndexDescriptors() {
if (indexDescriptorCache == null) {
indexDescriptorCache = listIndexDescriptors();
@@ -100,6 +81,11 @@ public IndexDescriptor findExactIndexDescriptor(Fields fields) {
return null;
}
+ public void markIndexDirty(IndexDescriptor indexDescriptor) {
+ Fields fields = indexDescriptor.getFields();
+ markDirty(fields, true);
+ }
+
@Override
public void close() {
// close all index maps
diff --git a/nitrite/src/main/java/org/dizitart/no2/collection/operation/IndexOperations.java b/nitrite/src/main/java/org/dizitart/no2/collection/operation/IndexOperations.java
index 6bba96ecb..3a6a6bc2d 100644
--- a/nitrite/src/main/java/org/dizitart/no2/collection/operation/IndexOperations.java
+++ b/nitrite/src/main/java/org/dizitart/no2/collection/operation/IndexOperations.java
@@ -29,6 +29,7 @@
/**
* @author Anindya Chatterjee
+ * @since 1.0
*/
class IndexOperations implements AutoCloseable {
private final String collectionName;
diff --git a/nitrite/src/main/java/org/dizitart/no2/collection/operation/ReadOperations.java b/nitrite/src/main/java/org/dizitart/no2/collection/operation/ReadOperations.java
index e9ac800d3..807b47d98 100644
--- a/nitrite/src/main/java/org/dizitart/no2/collection/operation/ReadOperations.java
+++ b/nitrite/src/main/java/org/dizitart/no2/collection/operation/ReadOperations.java
@@ -36,6 +36,7 @@
/**
* @author Anindya Chatterjee
+ * @since 1.0
*/
class ReadOperations {
private final String collectionName;
diff --git a/nitrite/src/main/java/org/dizitart/no2/collection/operation/WriteOperations.java b/nitrite/src/main/java/org/dizitart/no2/collection/operation/WriteOperations.java
index 9f491055b..8a7f73118 100644
--- a/nitrite/src/main/java/org/dizitart/no2/collection/operation/WriteOperations.java
+++ b/nitrite/src/main/java/org/dizitart/no2/collection/operation/WriteOperations.java
@@ -39,8 +39,9 @@
/**
* @author Anindya Chatterjee
+ * @since 1.0
*/
-@Slf4j
+@Slf4j(topic = "nitrite")
class WriteOperations {
private final DocumentIndexWriter documentIndexWriter;
private final ReadOperations readOperations;
diff --git a/nitrite/src/main/java/org/dizitart/no2/collection/operation/WriteResultImpl.java b/nitrite/src/main/java/org/dizitart/no2/collection/operation/WriteResultImpl.java
index 9e8a1d219..b210f20d6 100644
--- a/nitrite/src/main/java/org/dizitart/no2/collection/operation/WriteResultImpl.java
+++ b/nitrite/src/main/java/org/dizitart/no2/collection/operation/WriteResultImpl.java
@@ -24,6 +24,7 @@
/**
* @author Anindya Chatterjee
+ * @since 1.0
*/
@ToString
class WriteResultImpl implements WriteResult {
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/Constants.java b/nitrite/src/main/java/org/dizitart/no2/common/Constants.java
index c39095bb8..b2dcfc8f6 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/Constants.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/Constants.java
@@ -234,7 +234,7 @@ private Constants() {
public static final String SYNC_THREAD_NAME = "Sync." + NO2;
/**
- * The constant INITIAL_REVISION.
+ * The initial schema version of Nitrite database.
*/
public static final Integer INITIAL_SCHEMA_VERSION = 1;
}
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/DBNull.java b/nitrite/src/main/java/org/dizitart/no2/common/DBNull.java
index 93d6c143a..4f2c1985e 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/DBNull.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/DBNull.java
@@ -1,14 +1,10 @@
package org.dizitart.no2.common;
-import java.io.Serializable;
-
/**
- * This class acts as a surrogate for null key.
- *
* @author Anindya Chatterjee
* @since 1.0
*/
-public class DBNull extends DBValue implements Serializable {
+public class DBNull extends DBValue {
private static final long serialVersionUID = 1598819770L;
private static final DBNull instance = new DBNull();
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/DBValue.java b/nitrite/src/main/java/org/dizitart/no2/common/DBValue.java
index a1f67cd87..6ee3c5014 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/DBValue.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/DBValue.java
@@ -29,6 +29,7 @@
/**
* @author Anindya Chatterjee
+ * @since 4.0
*/
@Data
public class DBValue implements Comparable, Serializable {
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/FieldValues.java b/nitrite/src/main/java/org/dizitart/no2/common/FieldValues.java
index 56c300f98..32e020191 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/FieldValues.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/FieldValues.java
@@ -9,8 +9,9 @@
import java.util.List;
/**
- * Represents a {@link Fields} and their corresponding values from a document.
- *
+ * Represents a collection of field-value pairs, with methods to retrieve
+ * values by field name.
+ *
* @author Anindya Chatterjee
* @since 4.0
*/
@@ -20,18 +21,15 @@ public class FieldValues {
private Fields fields;
private List> values;
- /**
- * Instantiates a new Field values.
- */
public FieldValues() {
values = new ArrayList<>();
}
/**
- * Get the value of the field.
- *
- * @param field the field
- * @return the value
+ * Retrieves the value associated with a given field name.
+ *
+ * @param field the name of a field.
+ * @return the value.
*/
public Object get(String field) {
if (fields.getFieldNames().contains(field)) {
@@ -45,9 +43,9 @@ public Object get(String field) {
}
/**
- * Gets the {@link Fields}.
- *
- * @return the fields
+ * Returns the {@link Fields} object associated with this instance.
+ *
+ * @return an instance of the Fields class.
*/
public Fields getFields() {
if (fields != null) {
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/Fields.java b/nitrite/src/main/java/org/dizitart/no2/common/Fields.java
index bc89affb2..9ae330676 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/Fields.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/Fields.java
@@ -19,7 +19,8 @@
import static org.dizitart.no2.common.util.ValidationUtils.notNull;
/**
- * Represents a list of document fields.
+ * Represents a collection of document field names and provides methods for
+ * manipulating and comparing them.
*
* @author Anindya Chatterjee
* @since 4.0
@@ -29,7 +30,7 @@ public class Fields implements Comparable, Serializable {
private static final long serialVersionUID = 1601646404L;
/**
- * The Field names.
+ * The names of the fields.
*/
@Setter(AccessLevel.PACKAGE)
protected List fieldNames;
@@ -56,9 +57,8 @@ public static Fields withNames(String... fields) {
return f;
}
-
/**
- * Adds a new field name.
+ * Adds a field name to a list of field names and returns the updated list.
*
* @param field the field
* @return the fields
@@ -72,7 +72,7 @@ public Fields addField(String field) {
}
/**
- * Gets the field names.
+ * Gets an unmodifiable list of field names.
*
* @return the field names
*/
@@ -92,7 +92,8 @@ public boolean startsWith(Fields other) {
int length = Math.min(fieldNames.size(), other.fieldNames.size());
// if other is greater than it is not a prefix of this field
- if (other.fieldNames.size() > length) return false;
+ if (other.fieldNames.size() > length)
+ return false;
for (int i = 0; i < length; i++) {
String thisField = fieldNames.get(i);
@@ -120,7 +121,8 @@ public String toString() {
@Override
public int compareTo(Fields other) {
- if (other == null) return 1;
+ if (other == null)
+ return 1;
int fieldsSize = getFieldNames().size();
int otherFieldsSize = other.getFieldNames().size();
int result = Integer.compare(fieldsSize, otherFieldsSize);
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/PersistentCollection.java b/nitrite/src/main/java/org/dizitart/no2/common/PersistentCollection.java
index deb52da92..736a9abdc 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/PersistentCollection.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/PersistentCollection.java
@@ -31,10 +31,11 @@
import java.util.Collection;
+
/**
- * The interface Persistent collection.
+ * A persistent collection interface that provides methods to manage and manipulate data in a Nitrite database.
*
- * @param the type parameter
+ * @param the type of data stored in the collection.
* @author Anindya Chatterjee.
* @see NitriteCollection
* @see ObjectRepository
@@ -66,13 +67,14 @@ default void createIndex(String... fields) {
* The default indexing option is -
*
*
- * {@code indexOptions.setIndexType(IndexType.Unique);}
+ * {@code indexOptions.setIndexType(IndexType.Unique);}
*
*
*
* NOTE:
*
- * _id value of the document is always indexed. But full-text indexing is not supported on _id value.
+ * _id field is always indexed.
+ * Full-text indexing is not supported on _id value.
* Indexing on non-comparable value is not supported.
*
*
@@ -92,7 +94,6 @@ default void createIndex(String... fields) {
*/
void rebuildIndex(String... fields);
-
/**
* Gets a set of all indices in the collection.
*
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/RecordStream.java b/nitrite/src/main/java/org/dizitart/no2/common/RecordStream.java
index 2bfc34ea6..567f16b56 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/RecordStream.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/RecordStream.java
@@ -21,9 +21,11 @@
import java.util.*;
/**
- * Represents a record stream which can be iterated in a for loop.
+ * An interface representing a stream of records of type T.
+ * Provides methods to create, manipulate and iterate over a
+ * stream of records.
*
- * @param the type parameter
+ * @param the type parameter for the records in the stream
* @author Anindya Chatterjee.
* @since 1.0
*/
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/SortOrder.java b/nitrite/src/main/java/org/dizitart/no2/common/SortOrder.java
index 8353a2621..2165e6fe8 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/SortOrder.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/SortOrder.java
@@ -17,18 +17,18 @@
package org.dizitart.no2.common;
/**
- * An enum to specify a sort order.
+ * An enum is used to specify the sort order for sorting operations.
*
* @author Anindya Chatterjee
* @since 1.0
*/
public enum SortOrder {
/**
- * Ascending sort order.
+ * Represents the ascending sort order.
*/
Ascending,
/**
- * Descending sort order.
+ * Represents the descending sort order.
*/
Descending
}
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/SortableFields.java b/nitrite/src/main/java/org/dizitart/no2/common/SortableFields.java
index 7b2b67642..c268b0256 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/SortableFields.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/SortableFields.java
@@ -29,8 +29,8 @@
import static org.dizitart.no2.common.util.ValidationUtils.notNull;
/**
- * Represents a list of document field with
- * sorting direction for find query.
+ * Represents a collection of fields that can be sorted, with each field
+ * having a specified sort order.
*
* @author Anindya Chatterjee
* @since 4.0
@@ -65,7 +65,7 @@ public static SortableFields withNames(String... fields) {
}
/**
- * Adds the sort order for a field.
+ * Adds a field and its corresponding sort order to a list of sortable fields.
*
* @param field the field
* @param sortOrder the sort order
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/UnknownType.java b/nitrite/src/main/java/org/dizitart/no2/common/UnknownType.java
index db54acd0b..35e650c5c 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/UnknownType.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/UnknownType.java
@@ -1,8 +1,6 @@
package org.dizitart.no2.common;
/**
- * Represents an unknown type.
- *
* @author Anindya Chatterjee
* @since 4.0
*/
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/WriteResult.java b/nitrite/src/main/java/org/dizitart/no2/common/WriteResult.java
index 737ad7025..f5e2488ae 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/WriteResult.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/WriteResult.java
@@ -21,17 +21,16 @@
import org.dizitart.no2.common.util.Iterables;
/**
- * An interface to represent the result of a modification operation
- * on {@link NitriteCollection}. It provides a means to iterate over
- * all affected ids in the collection.
+ * An interface to represent the result of a write operation in Nitrite database.
+ * It is an iterable of {@link NitriteId}s of affected documents.
*
- * @author Anindya Chatterjee.
+ * @author Anindya Chatterjee
* @since 1.0
*/
public interface WriteResult extends Iterable {
/**
- * Gets the count of affected document in the collection.
+ * Gets the number of affected documents by the write operation.
*
* @return the affected document count.
*/
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/concurrent/ErrorAwareThreadFactory.java b/nitrite/src/main/java/org/dizitart/no2/common/concurrent/ErrorAwareThreadFactory.java
index 44a4e9557..85d350f33 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/concurrent/ErrorAwareThreadFactory.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/concurrent/ErrorAwareThreadFactory.java
@@ -27,7 +27,7 @@
* @author Anindya Chatterjee.
* @since 1.0
*/
-@Slf4j
+@Slf4j(topic = "nitrite")
public abstract class ErrorAwareThreadFactory implements ThreadFactory {
/**
* Creates a new {@link Thread}.
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/concurrent/ThreadPoolManager.java b/nitrite/src/main/java/org/dizitart/no2/common/concurrent/ThreadPoolManager.java
index bf3ace37d..35ab7883c 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/concurrent/ThreadPoolManager.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/concurrent/ThreadPoolManager.java
@@ -29,7 +29,7 @@
* @author Anindya Chatterjee.
* @since 4.0
*/
-@Slf4j
+@Slf4j(topic = "nitrite")
public class ThreadPoolManager {
private final static List threadPools;
private final static ExecutorService commonPool;
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/event/EventBus.java b/nitrite/src/main/java/org/dizitart/no2/common/event/EventBus.java
index e9bc7538b..1cc3e68b6 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/event/EventBus.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/event/EventBus.java
@@ -17,41 +17,15 @@
package org.dizitart.no2.common.event;
/**
- * Represents a generic publish/subscribe event bus interface.
- *
- * @param the event information type parameter
- * @param the event listener type parameter
* @author Anindya Chatterjee
* @since 1.0
*/
public interface EventBus extends AutoCloseable {
- /**
- * Registers an event listener to the event-bus.
- *
- * @param listener the event listener
- */
void register(EventListener listener);
- /**
- * De-registers an already registered event listener.
- *
- * @param listener the event listener
- */
void deregister(EventListener listener);
- /**
- * Posts an event to the event bus. All registered
- * event listeners for this event will receive the `eventInfo`
- * for further processing.
- *
- * Event processing is asynchronous.
- *
- * @param eventInfo the event related information
- */
void post(EventInfo eventInfo);
- /**
- * Closes this {@link EventBus} instance.
- * */
void close();
}
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/event/NitriteEventBus.java b/nitrite/src/main/java/org/dizitart/no2/common/event/NitriteEventBus.java
index d5b0c3ecd..3f08b5bb4 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/event/NitriteEventBus.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/event/NitriteEventBus.java
@@ -23,22 +23,15 @@
import java.util.concurrent.ExecutorService;
/**
- * An abstract implementation of {@link EventBus}.
- *
- * @param the event information type parameter
- * @param the event listener type parameter
* @author Anindya Chatterjee.
* @since 1.0
*/
public abstract class NitriteEventBus
- implements EventBus, AutoCloseable {
+ implements EventBus {
private final Set listeners;
private ExecutorService eventExecutor;
- /**
- * Instantiates a new Nitrite event bus.
- */
public NitriteEventBus() {
this.listeners = new CopyOnWriteArraySet<>();
}
@@ -65,11 +58,6 @@ public void close() {
}
}
- /**
- * Gets the {@link ExecutorService} that executes listeners' code.
- *
- * @return the {@link ExecutorService}.
- */
protected ExecutorService getEventExecutor() {
if (eventExecutor == null
|| eventExecutor.isShutdown()
@@ -79,11 +67,6 @@ protected ExecutorService getEventExecutor() {
return eventExecutor;
}
- /**
- * Gets a set of all event listeners.
- *
- * @return the event listeners
- */
protected Set getListeners() {
return listeners;
}
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/mapper/EntityConverter.java b/nitrite/src/main/java/org/dizitart/no2/common/mapper/EntityConverter.java
index f140cede0..e382f5cf9 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/mapper/EntityConverter.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/mapper/EntityConverter.java
@@ -20,8 +20,9 @@
import org.dizitart.no2.collection.Document;
/**
- * A class that implements this interface can be used to convert
- * entity into a database {@link Document} and back again.
+ * The {@link EntityConverter} interface is used to convert
+ * an entity of type {@link T} into a database {@link Document}
+ * and vice versa.
*
* @since 4.0
* @author Anindya Chatterjee
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/mapper/NitriteMapper.java b/nitrite/src/main/java/org/dizitart/no2/common/mapper/NitriteMapper.java
index 7bd083966..5d32f7e26 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/mapper/NitriteMapper.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/mapper/NitriteMapper.java
@@ -19,10 +19,10 @@
import org.dizitart.no2.common.module.NitritePlugin;
/**
- * Represents a mapper which will convert an object of one type to an object of another type.
+ * An interface that provides a method to try converting an object of one type to an object of another type.
*
* @author Anindya Chatterjee.
- * @since 4.0
+ * @since 1.0
*/
public interface NitriteMapper extends NitritePlugin {
/**
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/mapper/SimpleDocumentMapper.java b/nitrite/src/main/java/org/dizitart/no2/common/mapper/SimpleNitriteMapper.java
similarity index 94%
rename from nitrite/src/main/java/org/dizitart/no2/common/mapper/SimpleDocumentMapper.java
rename to nitrite/src/main/java/org/dizitart/no2/common/mapper/SimpleNitriteMapper.java
index ab40f0a97..df218cfad 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/mapper/SimpleDocumentMapper.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/mapper/SimpleNitriteMapper.java
@@ -30,19 +30,23 @@
/**
* A {@link NitriteMapper} based on {@link EntityConverter} implementation.
*
+ *
+ * This mapper is used by default in nitrite. It uses {@link EntityConverter} to
+ * convert an object and vice versa.
+ *
* @author Anindya Chatterjee.
* @since 4.0
*/
-public class SimpleDocumentMapper implements NitriteMapper {
+public class SimpleNitriteMapper implements NitriteMapper {
private final Set> valueTypes;
private final Map, EntityConverter>> converterRegistry;
/**
- * Instantiates a new {@link SimpleDocumentMapper}.
+ * Instantiates a new {@link SimpleNitriteMapper}.
*
* @param valueTypes the value types
*/
- public SimpleDocumentMapper(Class>... valueTypes) {
+ public SimpleNitriteMapper(Class>... valueTypes) {
this.valueTypes = new HashSet<>();
this.converterRegistry = new HashMap<>();
init(listOf(valueTypes));
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/meta/Attributes.java b/nitrite/src/main/java/org/dizitart/no2/common/meta/Attributes.java
index d338be0c3..ee4a32f27 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/meta/Attributes.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/meta/Attributes.java
@@ -28,7 +28,7 @@
import java.util.concurrent.ConcurrentHashMap;
/**
- * Represents metadata attributes of a collection.
+ * Represents metadata attributes of a {@link NitriteMap}.
*
* @author Anindya Chatterjee
* @since 1.0
@@ -125,12 +125,16 @@ public Attributes(String collection) {
set(UNIQUE_ID, UUID.randomUUID().toString());
}
+
/**
- * Set attributes.
- *
- * @param key the key
- * @param value the value
- * @return the attributes
+ * Adds a key-value pair to the attributes and returns the updated
+ * {@link Attributes} object.
+ *
+ * @param key The key is a string that represents the attribute name. It is used to identify the
+ * attribute in the attributes.
+ * @param value The value parameter is a string that represents the value to be associated with the
+ * given key in the attributes.
+ * @return The method is returning an instance of the Attributes class.
*/
public Attributes set(String key, String value) {
attributes.put(LAST_MODIFIED_TIME, Long.toString(System.currentTimeMillis()));
@@ -139,10 +143,11 @@ public Attributes set(String key, String value) {
}
/**
- * Get string value of an attribute.
- *
- * @param key the key
- * @return the string
+ * Retrieves the value associated with a given key from a {@link Attributes}.
+ *
+ * @param key The "key" parameter is a String that represents the key of the attribute that you
+ * want to retrieve from the attributes.
+ * @return The method is returning the value associated with the given key in the attributes.
*/
public String get(String key) {
return attributes.get(key);
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/meta/AttributesAware.java b/nitrite/src/main/java/org/dizitart/no2/common/meta/AttributesAware.java
index 8ae092dd4..4a791bac9 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/meta/AttributesAware.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/meta/AttributesAware.java
@@ -18,24 +18,11 @@
package org.dizitart.no2.common.meta;
/**
- * Interface to be implemented by database objects that wish to be
- * aware of their metadata attributes.
- *
* @author Anindya Chatterjee.
* @since 1.0
*/
public interface AttributesAware {
- /**
- * Returns the metadata attributes of an object.
- *
- * @return the meta data attributes.
- */
Attributes getAttributes();
- /**
- * Sets new meta data attributes.
- *
- * @param attributes new meta data attributes.
- */
void setAttributes(Attributes attributes);
}
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/module/NitriteModule.java b/nitrite/src/main/java/org/dizitart/no2/common/module/NitriteModule.java
index 4404d5ac7..ec2c2d12a 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/module/NitriteModule.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/module/NitriteModule.java
@@ -21,15 +21,14 @@
import static org.dizitart.no2.common.util.Iterables.setOf;
/**
- * Represents a nitrite plugin modules which may contains
- * one or more nitrite plugins.
+ * Represents a module encapsulating a set of {@link NitritePlugin} objects.
*
* @author Anindya Chatterjee
* @since 4.0
*/
public interface NitriteModule {
/**
- * Creates a {@link NitriteModule} from a set of {@link NitritePlugin}s.
+ * Creates a {@link NitriteModule} with a set of {@link NitritePlugin}s.
*
* @param plugins the plugins
* @return the nitrite module
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/module/NitritePlugin.java b/nitrite/src/main/java/org/dizitart/no2/common/module/NitritePlugin.java
index b7a16d21d..bc581d3ad 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/module/NitritePlugin.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/module/NitritePlugin.java
@@ -19,7 +19,8 @@
import org.dizitart.no2.NitriteConfig;
/**
- * Represents a nitrite database plugin component.
+ * Represents a plugin for working with Nitrite
+ * database and provides methods for initializing and closing the plugin.
*
* @author Anindya Chatterjee.
* @since 4.0
@@ -32,6 +33,9 @@ public interface NitritePlugin extends AutoCloseable {
*/
void initialize(NitriteConfig nitriteConfig);
+ /**
+ * Closes the plugin instance.
+ */
default void close() {
// this is to make NitritePlugin a functional interface
// and make close() not throw checked exception
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/module/PluginManager.java b/nitrite/src/main/java/org/dizitart/no2/common/module/PluginManager.java
index b724975d7..65e9c466f 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/module/PluginManager.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/module/PluginManager.java
@@ -22,7 +22,7 @@
import org.dizitart.no2.exceptions.NitriteIOException;
import org.dizitart.no2.exceptions.PluginException;
import org.dizitart.no2.index.*;
-import org.dizitart.no2.common.mapper.SimpleDocumentMapper;
+import org.dizitart.no2.common.mapper.SimpleNitriteMapper;
import org.dizitart.no2.common.mapper.NitriteMapper;
import org.dizitart.no2.store.NitriteStore;
import org.dizitart.no2.store.memory.InMemoryStoreModule;
@@ -31,15 +31,10 @@
import java.util.Map;
/**
- * The nitrite database plugin manager. It loads the nitrite plugins
- * before opening the database.
- *
- * @see NitriteModule
- * @see NitritePlugin
* @author Anindya Chatterjee.
* @since 4.0
*/
-@Slf4j
+@Slf4j(topic = "nitrite")
@Getter
public class PluginManager implements AutoCloseable {
private final Map indexerMap;
@@ -188,7 +183,7 @@ protected void loadInternalPlugins() {
if (nitriteMapper == null) {
log.debug("Loading mappable mapper");
- NitritePlugin plugin = new SimpleDocumentMapper();
+ NitritePlugin plugin = new SimpleNitriteMapper();
loadPlugin(plugin);
}
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/processors/Processor.java b/nitrite/src/main/java/org/dizitart/no2/common/processors/Processor.java
index 7c266efe8..ed6f9e381 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/processors/Processor.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/processors/Processor.java
@@ -26,7 +26,8 @@
import static org.dizitart.no2.common.util.DocumentUtils.createUniqueFilter;
/**
- * Represents a document processor.
+ * An interface that provides methods to process a document before
+ * writing it into database or after reading from the database.
*
* @author Anindya Chatterjee
* @since 4.0
@@ -50,9 +51,11 @@ public interface Processor {
default Document processAfterRead(Document document) { return document; }
/**
- * Processes all documents of a {@link PersistentCollection}.
- *
- * @param collection the collection to process
+ * Processes documents in a persistent collection, updates them,and saves the changes
+ * back to the collection.
+ *
+ * @param collection the collection to process. It can either be a
+ * {@link NitriteCollection} or an {@link ObjectRepository}.
*/
default void process(PersistentCollection> collection) {
NitriteCollection nitriteCollection = null;
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/processors/ProcessorChain.java b/nitrite/src/main/java/org/dizitart/no2/common/processors/ProcessorChain.java
index 3d31ad18a..ec8294d3f 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/processors/ProcessorChain.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/processors/ProcessorChain.java
@@ -23,36 +23,20 @@
import java.util.List;
/**
- * Represents a {@link Processor} chain. It executes a
- * list of processor on a document.
- *
* @author Anindya Chatterjee
* @since 4.0
*/
public class ProcessorChain implements Processor {
private final List processors;
- /**
- * Instantiates a new Processor chain.
- */
public ProcessorChain() {
processors = new ArrayList<>();
}
- /**
- * Adds a processor to the chain.
- *
- * @param processor the processor
- */
public void add(Processor processor) {
processors.add(processor);
}
- /**
- * Removes a processor from the chain.
- *
- * @param processor the processor
- */
public void remove(Processor processor) {
processors.remove(processor);
}
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/streams/BoundedStream.java b/nitrite/src/main/java/org/dizitart/no2/common/streams/BoundedStream.java
index cd876d937..0bc4a52d4 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/streams/BoundedStream.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/streams/BoundedStream.java
@@ -26,8 +26,6 @@
import java.util.NoSuchElementException;
/**
- * Represents a bounded document stream.
- *
* @since 1.0
* @author Anindya Chatterjee.
*/
@@ -36,13 +34,6 @@ public class BoundedStream implements RecordStream>
private final long skip;
private final long limit;
- /**
- * Instantiates a new Bounded document stream.
- *
- * @param skip the skip
- * @param limit the limit
- * @param recordStream the record stream
- */
public BoundedStream(Long skip, Long limit, RecordStream> recordStream) {
this.skip = skip;
this.limit = limit;
@@ -70,13 +61,6 @@ private static class BoundedIterator implements Iterator {
private final long limit;
private long pos;
- /**
- * Instantiates a new Bounded iterator.
- *
- * @param iterator the iterator
- * @param skip the skip
- * @param limit the limit
- */
public BoundedIterator(final Iterator extends T> iterator, final long skip, final long limit) {
if (iterator == null) {
throw new ValidationException("Iterator must not be null");
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/streams/ConcatStream.java b/nitrite/src/main/java/org/dizitart/no2/common/streams/ConcatStream.java
index faf1e18c2..fbebe7aa1 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/streams/ConcatStream.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/streams/ConcatStream.java
@@ -25,19 +25,12 @@
import java.util.*;
/**
- * Represents an concatenation of multiple distinct nitrite document stream.
- *
* @author Anindya Chatterjee
* @since 4.0
*/
public class ConcatStream implements RecordStream> {
private final Collection>> streams;
- /**
- * Instantiates a new Union stream.
- *
- * @param streams the streams
- */
public ConcatStream(Collection>> streams) {
this.streams = streams;
}
@@ -51,18 +44,10 @@ public Iterator> iterator() {
return new UnionStreamIterator(iteratorQueue);
}
- /**
- * The type Union stream iterator.
- */
private static class UnionStreamIterator implements Iterator> {
private final Queue>> iteratorQueue;
private Iterator> currentIterator;
- /**
- * Instantiates a new Union stream iterator.
- *
- * @param iteratorQueue the iterator queue
- */
public UnionStreamIterator(Queue>> iteratorQueue) {
this.iteratorQueue = iteratorQueue;
}
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/streams/DistinctStream.java b/nitrite/src/main/java/org/dizitart/no2/common/streams/DistinctStream.java
index 7e23b041f..e8e9a9a30 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/streams/DistinctStream.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/streams/DistinctStream.java
@@ -25,19 +25,12 @@
import java.util.*;
/**
- * Represents a document stream of distinct elements
- *
* @author Anindya Chatterjee
* @since 4.0
*/
public class DistinctStream implements RecordStream> {
private final RecordStream> rawStream;
- /**
- * Instantiates a new DistinctStream.
- *
- * @param rawStream the raw stream
- */
public DistinctStream(RecordStream> rawStream) {
this.rawStream = rawStream;
}
@@ -55,11 +48,6 @@ private static class DistinctStreamIterator implements Iterator nextPair;
private boolean nextPairSet = false;
- /**
- * Instantiates a new DistinctStreamIterator.
- *
- * @param iterator the iterator
- */
public DistinctStreamIterator(Iterator> iterator) {
this.iterator = iterator;
this.scannedIds = new HashSet<>(); // fastest lookup for ids - O(1)
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/streams/DocumentSorter.java b/nitrite/src/main/java/org/dizitart/no2/common/streams/DocumentSorter.java
index 64b7dc8ce..c150976e9 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/streams/DocumentSorter.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/streams/DocumentSorter.java
@@ -29,12 +29,6 @@
import java.util.List;
/**
- * Sorts documents based on the sort order provided.
- *
- *
- * By default null is considered the lowest value.
- *
- *
* @author Anindya Chatterjee
* @since 4.0
*/
@@ -42,12 +36,6 @@ public class DocumentSorter implements Comparator> {
private final Collator collator;
private final List> sortOrder;
- /**
- * Instantiates a new Document sorter.
- *
- * @param collator the collator
- * @param sortOrder the sort order
- */
public DocumentSorter(Collator collator, List> sortOrder) {
this.collator = collator;
this.sortOrder = sortOrder;
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/streams/DocumentStream.java b/nitrite/src/main/java/org/dizitart/no2/common/streams/DocumentStream.java
index 14aff3ddf..3a2b96e16 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/streams/DocumentStream.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/streams/DocumentStream.java
@@ -34,8 +34,6 @@
import java.util.Iterator;
/**
- * Represents a nitrite document stream.
- *
* @since 4.0
* @author Anindya Chatterjee.
*/
@@ -46,12 +44,6 @@ public class DocumentStream implements DocumentCursor {
@Getter @Setter
private FindPlan findPlan;
- /**
- * Instantiates a new Document stream.
- *
- * @param recordStream the record stream
- * @param processorChain the processor chain
- */
public DocumentStream(RecordStream> recordStream,
ProcessorChain processorChain) {
this.recordStream = recordStream;
@@ -96,12 +88,6 @@ private static class DocumentCursorIterator implements Iterator {
private final Iterator> iterator;
private final ProcessorChain processorChain;
- /**
- * Instantiates a new Document cursor iterator.
- *
- * @param iterator the iterator
- * @param processorChain the processor chain
- */
DocumentCursorIterator(Iterator> iterator,
ProcessorChain processorChain) {
this.iterator = iterator;
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/streams/FilteredStream.java b/nitrite/src/main/java/org/dizitart/no2/common/streams/FilteredStream.java
index 058f31431..9ee59bf4e 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/streams/FilteredStream.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/streams/FilteredStream.java
@@ -29,8 +29,6 @@
import java.util.NoSuchElementException;
/**
- * Represents a filtered nitrite document stream.
- *
* @author Anindya Chatterjee.
* @since 4.0
*/
@@ -38,12 +36,6 @@ public class FilteredStream implements RecordStream> {
private final RecordStream> recordStream;
private final Filter filter;
- /**
- * Instantiates a new Filtered stream.
- *
- * @param recordStream the record stream
- * @param filter the filter
- */
public FilteredStream(RecordStream> recordStream, Filter filter) {
this.recordStream = recordStream;
this.filter = filter;
@@ -61,21 +53,12 @@ public Iterator> iterator() {
return new FilteredIterator(iterator, filter);
}
- /**
- * The type Filtered iterator.
- */
private static class FilteredIterator implements Iterator> {
private final Iterator> iterator;
private final Filter filter;
private Pair nextPair;
private boolean nextPairSet = false;
- /**
- * Instantiates a new Filtered iterator.
- *
- * @param iterator the iterator
- * @param filter the filter
- */
public FilteredIterator(Iterator> iterator, Filter filter) {
this.iterator = iterator;
this.filter = filter;
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/streams/IndexedStream.java b/nitrite/src/main/java/org/dizitart/no2/common/streams/IndexedStream.java
index d94368fb9..ab86c9fdd 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/streams/IndexedStream.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/streams/IndexedStream.java
@@ -27,8 +27,6 @@
import java.util.Set;
/**
- * Represents a nitrite stream backed by an index.
- *
* @author Anindya Chatterjee
* @since 4.0
*/
@@ -36,12 +34,6 @@ public class IndexedStream implements RecordStream> {
private final NitriteMap nitriteMap;
private final Set nitriteIds;
- /**
- * Instantiates a new Indexed stream.
- *
- * @param nitriteIds the nitrite ids
- * @param nitriteMap the nitrite map
- */
public IndexedStream(Set nitriteIds,
NitriteMap nitriteMap) {
this.nitriteIds = nitriteIds;
@@ -53,19 +45,10 @@ public Iterator> iterator() {
return new IndexedStreamIterator(nitriteIds.iterator(), nitriteMap);
}
- /**
- * The type Indexed stream iterator.
- */
private static class IndexedStreamIterator implements Iterator> {
private final Iterator iterator;
private final NitriteMap nitriteMap;
- /**
- * Instantiates a new Indexed stream iterator.
- *
- * @param iterator the iterator
- * @param nitriteMap the nitrite map
- */
IndexedStreamIterator(Iterator iterator,
NitriteMap nitriteMap) {
this.iterator = iterator;
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/streams/JoinedDocumentStream.java b/nitrite/src/main/java/org/dizitart/no2/common/streams/JoinedDocumentStream.java
index aeb65ea11..0ebc52175 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/streams/JoinedDocumentStream.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/streams/JoinedDocumentStream.java
@@ -34,8 +34,6 @@
import static org.dizitart.no2.common.util.ObjectUtils.deepEquals;
/**
- * Represents a joined document stream.
- *
* @author Anindya Chatterjee.
* @since 1.0
*/
@@ -45,14 +43,6 @@ public class JoinedDocumentStream implements RecordStream {
private final Lookup lookup;
private final ProcessorChain processorChain;
- /**
- * Instantiates a new Joined document stream.
- *
- * @param recordStream the record stream
- * @param foreignCursor the foreign cursor
- * @param lookup the lookup
- * @param processorChain the processor chain
- */
JoinedDocumentStream(RecordStream> recordStream,
DocumentCursor foreignCursor,
Lookup lookup, ProcessorChain processorChain) {
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/streams/MutatedObjectStream.java b/nitrite/src/main/java/org/dizitart/no2/common/streams/MutatedObjectStream.java
index bbf211fb7..558bf81ba 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/streams/MutatedObjectStream.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/streams/MutatedObjectStream.java
@@ -28,6 +28,7 @@
/**
* @author Anindya Chatterjee.
+ * @since 4.0
*/
public class MutatedObjectStream implements RecordStream {
private final RecordStream recordIterable;
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/streams/ProjectedDocumentStream.java b/nitrite/src/main/java/org/dizitart/no2/common/streams/ProjectedDocumentStream.java
index fac78cbd4..a08e62b3e 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/streams/ProjectedDocumentStream.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/streams/ProjectedDocumentStream.java
@@ -28,8 +28,6 @@
import java.util.Iterator;
/**
- * Represents a projected nitrite document stream.
- *
* @author Anindya Chatterjee.
* @since 1.0
*/
@@ -38,13 +36,6 @@ public class ProjectedDocumentStream implements RecordStream {
private final Document projection;
private final ProcessorChain processorChain;
- /**
- * Instantiates a new Projected document stream.
- *
- * @param recordStream the record stream
- * @param projection the projection
- * @param processorChain the processor chain
- */
public ProjectedDocumentStream(RecordStream> recordStream,
Document projection, ProcessorChain processorChain) {
this.recordStream = recordStream;
@@ -70,12 +61,6 @@ private static class ProjectedDocumentIterator implements Iterator {
private Document nextElement = null;
private final Document projection;
- /**
- * Instantiates a new Projected document iterator.
- *
- * @param iterator the iterator
- * @param processorChain the processor chain
- */
ProjectedDocumentIterator(Iterator> iterator,
ProcessorChain processorChain,
Document projection) {
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/streams/SortedDocumentStream.java b/nitrite/src/main/java/org/dizitart/no2/common/streams/SortedDocumentStream.java
index 8c89985c2..ed940bea3 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/streams/SortedDocumentStream.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/streams/SortedDocumentStream.java
@@ -29,8 +29,6 @@
import java.util.List;
/**
- * Represents a sorted nitrite document stream
- *
* @since 4.0
* @author Anindya Chatterjee.
*/
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/tuples/Pair.java b/nitrite/src/main/java/org/dizitart/no2/common/tuples/Pair.java
index cf2298ad9..18e733132 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/tuples/Pair.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/tuples/Pair.java
@@ -25,11 +25,12 @@
import java.io.ObjectOutputStream;
import java.io.Serializable;
+
/**
- * Represents a pair.
+ * A simple generic class representing a pair of values.
*
- * @param the type parameter
- * @param the type parameter
+ * @param the type of the first value in the pair
+ * @param the type of the second value in the pair
* @author Anindya Chatterjee.
* @since 4.0
*/
diff --git a/nitrite/src/main/java/org/dizitart/no2/common/tuples/Quartet.java b/nitrite/src/main/java/org/dizitart/no2/common/tuples/Quartet.java
index 6fb0cb6d7..a22becf4f 100644
--- a/nitrite/src/main/java/org/dizitart/no2/common/tuples/Quartet.java
+++ b/nitrite/src/main/java/org/dizitart/no2/common/tuples/Quartet.java
@@ -10,12 +10,12 @@
import java.io.Serializable;
/**
- * Represents a quartet.
+ * A tuple of four elements.
*
- * @param the type parameter
- * @param