repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
|---|---|---|---|---|---|---|
null |
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/function/sortedset/PopFunction.java
|
package org.infinispan.multimap.impl.function.sortedset;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.functional.EntryView;
import org.infinispan.multimap.impl.ExternalizerIds;
import org.infinispan.multimap.impl.SortedSetBucket;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collection;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
/**
* Serializable function used by
* {@link org.infinispan.multimap.impl.EmbeddedMultimapSortedSetCache#pop(Object, double, long)}
*
* @author Katia Aresti
* @see <a href="http://infinispan.org/documentation/">Marshalling of Functions</a>
* @since 15.0
*/
public final class PopFunction<K, V> implements SortedSetBucketBaseFunction<K, V, Collection<SortedSetBucket.ScoredValue<V>>> {
public static final AdvancedExternalizer<PopFunction> EXTERNALIZER = new Externalizer();
private final boolean min;
private final long count;
public PopFunction(boolean min, long count) {
this.min = min;
this.count = count;
}
@Override
public Collection<SortedSetBucket.ScoredValue<V>> apply(EntryView.ReadWriteEntryView<K, SortedSetBucket<V>> entryView) {
Optional<SortedSetBucket<V>> existing = entryView.peek();
if (existing.isPresent()) {
SortedSetBucket<V> sortedSetBucket = existing.get();
Collection<SortedSetBucket.ScoredValue<V>> poppedValues = sortedSetBucket.pop(min, count);
if (sortedSetBucket.size() == 0) {
entryView.remove();
}
return poppedValues;
}
return Collections.emptyList();
}
private static class Externalizer implements AdvancedExternalizer<PopFunction> {
@Override
public Set<Class<? extends PopFunction>> getTypeClasses() {
return Collections.singleton(PopFunction.class);
}
@Override
public Integer getId() {
return ExternalizerIds.SORTED_SET_POP_FUNCTION;
}
@Override
public void writeObject(ObjectOutput output, PopFunction object) throws IOException {
output.writeBoolean(object.min);
output.writeLong(object.count);
}
@Override
public PopFunction readObject(ObjectInput input) throws IOException {
return new PopFunction(input.readBoolean(), input.readLong());
}
}
}
| 2,403
| 32.388889
| 127
|
java
|
null |
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/internal/MultimapObjectWrapper.java
|
package org.infinispan.multimap.impl.internal;
import org.infinispan.commons.util.Util;
import org.infinispan.marshall.protostream.impl.MarshallableUserObject;
import org.infinispan.protostream.annotations.ProtoFactory;
import org.infinispan.protostream.annotations.ProtoField;
import org.infinispan.protostream.annotations.ProtoTypeId;
import java.util.Arrays;
import java.util.Objects;
import static org.infinispan.commons.marshall.ProtoStreamTypeIds.MULTIMAP_OBJECT_WRAPPER;
/**
* Wrapper for objects stored in multimap buckets.
* <p>
* This wrapper provides an implementation for {@link #equals(Object)} and {@link #hashCode()} methods to the underlying
* object. Making the wrapper fit to store elements in HashMaps or Sets.
*
* @param <T>: Type of the underlying object.
* @since 15.0
*/
@ProtoTypeId(MULTIMAP_OBJECT_WRAPPER)
public class MultimapObjectWrapper<T> implements Comparable<MultimapObjectWrapper> {
final T object;
public MultimapObjectWrapper(T object) {
this.object = object;
}
@ProtoFactory
MultimapObjectWrapper(MarshallableUserObject<T> wrapper) {
this(wrapper.get());
}
public T get() {
return object;
}
@ProtoField(number = 1)
MarshallableUserObject<T> wrapper() {
return new MarshallableUserObject<>(object);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof MultimapObjectWrapper)) return false;
MultimapObjectWrapper<?> other = (MultimapObjectWrapper<?>) obj;
if (object instanceof byte[] && other.object instanceof byte[])
return Arrays.equals((byte[]) object, (byte[]) other.object);
return Objects.equals(object, other.object);
}
@Override
public int hashCode() {
if (object instanceof byte[])
return java.util.Arrays.hashCode((byte[]) object);
return Objects.hashCode(object);
}
@Override
public int compareTo(MultimapObjectWrapper other) {
if (other == null) {
throw new NullPointerException();
}
if (this.equals(other)) {
return 0;
}
if (this.object instanceof Comparable && other.object instanceof Comparable) {
return ((Comparable) this.object).compareTo(other.object);
}
if (object instanceof byte[] && other.object instanceof byte[]) {
return Arrays.compare((byte[]) object, (byte[]) other.object);
}
throw new ClassCastException("can't compare");
}
@Override
public String toString() {
if (object instanceof byte[]) {
return "MultimapObjectWrapper{" + "object=" + Util.hexDump((byte[])object) + '}';
}
return "MultimapObjectWrapper{" + "object=" + object + '}';
}
}
| 2,751
| 28.276596
| 120
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/test/java/org/infinispan/query/remote/impl/QueryFacadeImplTest.java
|
package org.infinispan.query.remote.impl;
import static org.testng.AssertJUnit.assertEquals;
import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;
import org.infinispan.server.core.QueryFacade;
import org.testng.annotations.Test;
/**
* @author anistor@redhat.com
* @since 6.0
*/
@Test(groups = "functional", testName = "query.remote.impl.QueryFacadeImplTest")
public class QueryFacadeImplTest {
/**
* Ensure there is exactly one loadable provider for QueryFacade.
*/
public void testProvider() {
List<QueryFacade> implementations = new ArrayList<>();
for (QueryFacade impl : ServiceLoader.load(QueryFacade.class)) {
implementations.add(impl);
}
assertEquals(1, implementations.size());
assertEquals(QueryFacadeImpl.class, implementations.get(0).getClass());
}
}
| 856
| 25.78125
| 80
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/test/java/org/infinispan/query/remote/impl/ProtobufFieldIndexingMetadataTest.java
|
package org.infinispan.query.remote.impl;
import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.protostream.DescriptorParserException;
import org.infinispan.protostream.FileDescriptorSource;
import org.infinispan.protostream.SerializationContext;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.transaction.TransactionMode;
import org.testng.annotations.Test;
/**
* Test that ProtobufIndexedFieldProvider correctly identifies indexed fields based on the protostream annotations
* applied in the test model (bank.proto).
*
* @author anistor@redhat.com
* @since 9.0
*/
@Test(groups = "functional", testName = "query.remote.impl.ProtobufFieldIndexingMetadataTest")
public class ProtobufFieldIndexingMetadataTest extends SingleCacheManagerTest {
private static final class TestSCI implements SerializationContextInitializer {
@Override
public String getProtoFile() {
return "/** @Indexed */ message User {\n" +
"\n" +
" /** @Field(store = Store.YES) */ required string name = 1;\n" +
"\n" +
" required string surname = 2;\n" +
"\n" +
" /** @Indexed */" +
" message Address {\n" +
" /** @Field(store = Store.YES) */ required string street = 10;\n" +
" required string postCode = 20;\n" +
" }\n" +
"\n" +
" /** @Field(store = Store.YES) */ repeated Address indexedAddresses = 3;\n" +
"\n" +
" /** @Field(index = Index.NO) */ repeated Address unindexedAddresses = 4;\n" +
"}\n";
}
@Override
public String getProtoFileName() {
return "user_definition.proto";
}
@Override
public void registerSchema(SerializationContext serCtx) {
serCtx.registerProtoFiles(FileDescriptorSource.fromString(getProtoFileName(), getProtoFile()));
}
@Override
public void registerMarshallers(SerializationContext ctx) {
}
}
protected EmbeddedCacheManager createCacheManager() throws Exception {
ConfigurationBuilder cfg = getDefaultStandaloneCacheConfig(true);
cfg.transaction().transactionMode(TransactionMode.TRANSACTIONAL)
.indexing().enable()
.storage(LOCAL_HEAP)
.addIndexedEntity("User");
return TestCacheManagerFactory.createServerModeCacheManager(new TestSCI(), cfg);
}
public void testProtobufFieldIndexingMetadata() {
SerializationContext serCtx = ProtobufMetadataManagerImpl.getSerializationContext(cacheManager);
ProtobufFieldIndexingMetadata userIndexedFieldProvider = new ProtobufFieldIndexingMetadata(serCtx.getMessageDescriptor("User"));
ProtobufFieldIndexingMetadata addressIndexedFieldProvider = new ProtobufFieldIndexingMetadata(serCtx.getMessageDescriptor("User.Address"));
// try top level attributes
assertTrue(userIndexedFieldProvider.isIndexed(new String[]{"name"}));
assertFalse(userIndexedFieldProvider.isIndexed(new String[]{"surname"}));
assertTrue(addressIndexedFieldProvider.isIndexed(new String[]{"street"}));
assertFalse(addressIndexedFieldProvider.isIndexed(new String[]{"postCode"}));
// try nested attributes
assertTrue(userIndexedFieldProvider.isIndexed(new String[]{"indexedAddresses", "street"}));
assertFalse(userIndexedFieldProvider.isIndexed(new String[]{"indexedAddresses", "postCode"}));
assertFalse(userIndexedFieldProvider.isIndexed(new String[]{"unindexedAddresses", "street"}));
assertFalse(userIndexedFieldProvider.isIndexed(new String[]{"unindexedAddresses", "postCode"}));
}
@Test(expectedExceptions = DescriptorParserException.class, expectedExceptionsMessageRegExp = "java.lang.IllegalStateException: Cannot specify an analyzer for field test.User3.name unless the field is analyzed.")
public void testAnalyzerForNotAnalyzedField() {
String testProto = "package test;\n" +
"/* @Indexed */ message User3 {\n" +
" /* @Field(store=Store.NO, index=Index.YES, analyze=Analyze.NO, analyzer=@Analyzer(definition=\"standard\")) */" +
" required string name = 1;\n" +
"}";
SerializationContext serCtx = ProtobufMetadataManagerImpl.getSerializationContext(cacheManager);
serCtx.registerProtoFiles(FileDescriptorSource.fromString("test2.proto", testProto));
}
}
| 4,874
| 45.875
| 215
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/test/java/org/infinispan/query/remote/impl/ProtobufMetadataCacheStartedTest.java
|
package org.infinispan.query.remote.impl;
import static org.testng.AssertJUnit.assertTrue;
import org.infinispan.commons.test.CommonsTestingUtil;
import org.infinispan.commons.util.Util;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.query.remote.client.ProtobufMetadataManagerConstants;
import org.infinispan.test.AbstractInfinispanTest;
import org.infinispan.test.MultiCacheManagerCallable;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "query.remote.impl.ProtobufMetadataCacheStartedTest")
public class ProtobufMetadataCacheStartedTest extends AbstractInfinispanTest {
protected EmbeddedCacheManager createCacheManager(String persistentStateLocation) throws Exception {
GlobalConfigurationBuilder global = new GlobalConfigurationBuilder().clusteredDefault();
global.globalState().enable().persistentLocation(persistentStateLocation);
return TestCacheManagerFactory.createClusteredCacheManager(global, new ConfigurationBuilder());
}
public void testMetadataCacheStarted() throws Exception {
String persistentStateLocation = CommonsTestingUtil.tmpDirectory(getClass());
Util.recursiveFileRemove(persistentStateLocation);
final String persistentStateLocation1 = persistentStateLocation + "/1";
final String persistentStateLocation2 = persistentStateLocation + "/2";
TestingUtil.withCacheManagers(new MultiCacheManagerCallable(createCacheManager(persistentStateLocation1),
createCacheManager(persistentStateLocation2)) {
@Override
public void call() {
assertTrue(cms[0].isRunning(ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME));
assertTrue(cms[1].isRunning(ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME));
}
});
}
}
| 2,125
| 48.44186
| 113
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/test/java/org/infinispan/query/remote/impl/ProtobufMetadataCachePreserveStateAcrossRestartsTest.java
|
package org.infinispan.query.remote.impl;
import static java.util.Collections.singletonList;
import static org.infinispan.test.TestingUtil.extractGlobalComponent;
import static org.infinispan.test.TestingUtil.setOf;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import java.util.List;
import java.util.stream.Collectors;
import org.infinispan.Cache;
import org.infinispan.commons.test.CommonsTestingUtil;
import org.infinispan.commons.util.Util;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.manager.CacheContainer;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.marshall.protostream.impl.SerializationContextRegistry;
import org.infinispan.protostream.ImmutableSerializationContext;
import org.infinispan.protostream.descriptors.Descriptor;
import org.infinispan.protostream.impl.AnnotatedDescriptorImpl;
import org.infinispan.query.remote.ProtobufMetadataManager;
import org.infinispan.query.remote.client.ProtobufMetadataManagerConstants;
import org.infinispan.test.AbstractInfinispanTest;
import org.infinispan.test.CacheManagerCallable;
import org.infinispan.test.MultiCacheManagerCallable;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "query.remote.impl.ProtobufMetadataCachePreserveStateAcrossRestartsTest")
public class ProtobufMetadataCachePreserveStateAcrossRestartsTest extends AbstractInfinispanTest {
protected EmbeddedCacheManager createCacheManager(String persistentStateLocation) throws Exception {
GlobalConfigurationBuilder global = new GlobalConfigurationBuilder().clusteredDefault();
global.globalState().enable().persistentLocation(persistentStateLocation);
EmbeddedCacheManager cacheManager = TestCacheManagerFactory.createClusteredCacheManager(global, new ConfigurationBuilder());
cacheManager.getCache();
return cacheManager;
}
public void testStatePreserved1Node() throws Exception {
String persistentStateLocation = CommonsTestingUtil.tmpDirectory(this.getClass());
Util.recursiveFileRemove(persistentStateLocation);
TestingUtil.withCacheManager(new CacheManagerCallable(createCacheManager(persistentStateLocation)) {
@Override
public void call() {
insertSchemas(cm);
verifySchemas(cm);
}
});
TestingUtil.withCacheManager(new CacheManagerCallable(createCacheManager(persistentStateLocation)) {
@Override
public void call() {
verifySchemas(cm);
}
});
}
public void testStatePreserved2Nodes() throws Exception {
String persistentStateLocation = CommonsTestingUtil.tmpDirectory(this.getClass());
Util.recursiveFileRemove(persistentStateLocation);
final String persistentStateLocation1 = persistentStateLocation + "/1";
final String persistentStateLocation2 = persistentStateLocation + "/2";
TestingUtil.withCacheManagers(new MultiCacheManagerCallable(createCacheManager(persistentStateLocation1),
createCacheManager(persistentStateLocation2)) {
@Override
public void call() {
insertSchemas(cms[0]);
verifySchemas(cms[0]);
verifySchemas(cms[1]);
}
});
TestingUtil.withCacheManagers(new MultiCacheManagerCallable(createCacheManager(persistentStateLocation1),
createCacheManager(persistentStateLocation2)) {
@Override
public void call() {
verifySchemas(cms[0]);
verifySchemas(cms[0]);
}
});
}
private void insertSchemas(EmbeddedCacheManager cm) {
Cache<String, String> protobufMetadaCache = cm.getCache(ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME);
// Schemas that are invalid until A.proto is inserted
protobufMetadaCache.put("D.proto", "import \"B.proto\";\nimport \"C.proto\";\npackage D;\n" +
"message M {\nrequired string s = 1;\n}");
assertFilesWithErrors(cm, "D.proto");
protobufMetadaCache.put("C.proto", "import \"A.proto\";\nimport \"B.proto\";\npackage C;");
assertFilesWithErrors(cm, "D.proto", "C.proto");
protobufMetadaCache.put("B.proto", "import \"A.proto\";\npackage B;");
assertFilesWithErrors(cm, "D.proto", "C.proto", "B.proto");
protobufMetadaCache.put("A.proto", "package A;");
assertFilesWithErrors(cm);
// Schemas with errors
protobufMetadaCache.put("E.proto", "import \"E.proto\";\npackage E;");
protobufMetadaCache.put("F.proto", "import \"E.proto\";\nimport \"X.proto\";\npackage E;");
assertFilesWithErrors(cm, "E.proto", "F.proto");
}
private void verifySchemas(CacheContainer manager) {
assertFiles(manager, "A.proto", "B.proto", "C.proto", "D.proto", "E.proto", "F.proto");
assertFilesWithErrors(manager, "E.proto", "F.proto");
SerializationContextRegistry scr = extractGlobalComponent(manager, SerializationContextRegistry.class);
ImmutableSerializationContext serializationContext = scr.getUserCtx();
Descriptor mDescriptor = serializationContext.getMessageDescriptor("D.M");
assertNotNull(mDescriptor);
List<String> fields = mDescriptor.getFields().stream()
.map(AnnotatedDescriptorImpl::getName)
.collect(Collectors.toList());
assertEquals(singletonList("s"), fields);
}
private void assertFilesWithErrors(CacheContainer manager, String... expectedFileNames) {
ProtobufMetadataManager pmm = extractGlobalComponent(manager, ProtobufMetadataManager.class);
assertEquals(setOf(expectedFileNames), setOf(pmm.getFilesWithErrors()));
for (String fileName : expectedFileNames) {
assertNotNull(pmm.getFileErrors(fileName));
}
}
private void assertFiles(CacheContainer manager, String... expectedFileNames) {
ProtobufMetadataManager pmm = extractGlobalComponent(manager, ProtobufMetadataManager.class);
assertEquals(setOf(expectedFileNames), setOf(pmm.getProtofileNames()));
}
}
| 6,473
| 45.913043
| 130
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/test/java/org/infinispan/query/remote/impl/ProtobufMetadataManagerInterceptorTest.java
|
package org.infinispan.query.remote.impl;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
import static org.testng.AssertJUnit.fail;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletionException;
import org.infinispan.Cache;
import org.infinispan.commons.CacheException;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.functional.FunctionalMap;
import org.infinispan.functional.impl.FunctionalMapImpl;
import org.infinispan.functional.impl.ReadWriteMapImpl;
import org.infinispan.interceptors.locking.PessimisticLockingInterceptor;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.query.remote.client.ProtobufMetadataManagerConstants;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.infinispan.transaction.LockingMode;
import org.infinispan.transaction.TransactionMode;
import org.infinispan.util.concurrent.IsolationLevel;
import org.infinispan.util.concurrent.locks.LockManager;
import org.testng.annotations.Test;
@CleanupAfterMethod
@Test(groups = "functional", testName = "query.remote.impl.ProtobufMetadataManagerInterceptorTest")
public class ProtobufMetadataManagerInterceptorTest extends MultipleCacheManagersTest {
@Override
protected void createCacheManagers() throws Throwable {
//todo [anistor] test with ST, with store , test with manual TX, with batching, with HotRod
addClusterEnabledCacheManager(makeCfg());
addClusterEnabledCacheManager(makeCfg());
waitForClusterToForm();
}
private ConfigurationBuilder makeCfg() {
ConfigurationBuilder cfg = new ConfigurationBuilder();
cfg.transaction()
.transactionMode(TransactionMode.TRANSACTIONAL).invocationBatching().enable()
.clustering().cacheMode(CacheMode.REPL_SYNC)
.clustering()
.stateTransfer().fetchInMemoryState(true)
.transaction().lockingMode(LockingMode.PESSIMISTIC)
.locking().isolationLevel(IsolationLevel.READ_COMMITTED).useLockStriping(false)
.customInterceptors().addInterceptor()
.interceptor(new ProtobufMetadataManagerInterceptor()).after(PessimisticLockingInterceptor.class);
return cfg;
}
public void testValidatePut() {
Cache<String, String> cache0 = cache(0);
Cache<String, String> cache1 = cache(1);
assertTrue(cache0.isEmpty());
assertTrue(cache1.isEmpty());
try {
cache(0).put(42, "import \"test.proto\";");
fail();
} catch (CacheException e) {
assertEquals("ISPN028007: The key must be a String : class java.lang.Integer", e.getMessage());
}
try {
cache(0).put("some.proto", 42);
fail();
} catch (CacheException e) {
assertEquals("ISPN028008: The value must be a String : class java.lang.Integer", e.getMessage());
}
try {
cache0.put("some.xml", "import \"test.proto\";");
fail();
} catch (CacheException e) {
assertEquals("ISPN028009: The key must be a String ending with \".proto\" : some.xml", e.getMessage());
}
cache0.put("test.proto", "package x");
assertEquals("test.proto", cache0.get(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX));
assertEquals("test.proto", cache1.get(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX));
cache0.remove("test.proto");
assertTrue(cache0.isEmpty());
assertTrue(cache1.isEmpty());
Map<String, String> map = new HashMap<>();
map.put("a.proto", "package a");
map.put("b.proto", "package b;");
cache0.putAll(map);
assertEquals("a.proto", cache0.get(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX));
assertEquals("a.proto", cache1.get(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX));
assertEquals(4, cache0.size());
assertEquals(4, cache1.size());
assertNoTransactionsAndLocks();
}
public void testValidateReplace() {
Cache<String, String> cache0 = cache(0);
Cache<String, String> cache1 = cache(1);
assertTrue(cache0.isEmpty());
assertTrue(cache1.isEmpty());
String value = "package X;";
cache0.put("test.proto", value);
assertEquals(1, cache0.size());
assertEquals(1, cache1.size());
assertEquals(value, cache0.get("test.proto"));
assertEquals(value, cache1.get("test.proto"));
String newValue = "package XYX";
cache0.replace("test.proto", newValue);
assertEquals("test.proto", cache0.get(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX));
assertEquals("test.proto", cache1.get(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX));
assertEquals(3, cache0.size());
assertEquals(3, cache1.size());
assertEquals(newValue, cache0.get("test.proto"));
assertEquals(newValue, cache1.get("test.proto"));
assertNoTransactionsAndLocks();
}
public void testStatusAfterPut() {
Cache<String, String> cache0 = cache(0);
Cache<String, String> cache1 = cache(1);
assertTrue(cache0.isEmpty());
assertTrue(cache1.isEmpty());
String value = "import \"missing.proto\";";
cache0.put("test.proto", value);
assertEquals(value, cache0.get("test.proto"));
assertEquals(value, cache1.get("test.proto"));
assertEquals("Import 'missing.proto' not found", cache0.get("test.proto.errors"));
assertEquals("test.proto", cache0.get(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX));
assertEquals("Import 'missing.proto' not found", cache1.get("test.proto.errors"));
assertEquals("test.proto", cache1.get(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX));
value = "package foobar;";
cache0.put("test.proto", value);
assertEquals(value, cache0.get("test.proto"));
assertEquals(value, cache1.get("test.proto"));
assertFalse(cache0.containsKey("test.proto.errors"));
assertFalse(cache1.containsKey("test.proto.errors"));
assertFalse(cache0.containsKey(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX));
assertFalse(cache1.containsKey(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX));
assertNoTransactionsAndLocks();
}
public void testStatusAfterPutIfAbsent() {
Cache<String, String> cache0 = cache(0);
Cache<String, String> cache1 = cache(1);
assertTrue(cache0.isEmpty());
assertTrue(cache1.isEmpty());
String value = "import \"missing.proto\";";
cache0.putIfAbsent("test.proto", value);
assertEquals(value, cache0.get("test.proto"));
assertEquals(value, cache1.get("test.proto"));
assertEquals("Import 'missing.proto' not found", cache0.get("test.proto.errors"));
assertEquals("test.proto", cache0.get(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX));
assertEquals("Import 'missing.proto' not found", cache1.get("test.proto.errors"));
assertEquals("test.proto", cache1.get(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX));
cache0.putIfAbsent("test.proto", "package foobar;");
assertEquals(value, cache0.get("test.proto"));
assertEquals(value, cache1.get("test.proto"));
assertEquals("Import 'missing.proto' not found", cache0.get("test.proto.errors"));
assertEquals("test.proto", cache0.get(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX));
assertEquals("Import 'missing.proto' not found", cache1.get("test.proto.errors"));
assertEquals("test.proto", cache1.get(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX));
value = "package foobar;";
cache0.put("test.proto", value);
assertEquals(value, cache0.get("test.proto"));
assertEquals(value, cache1.get("test.proto"));
assertFalse(cache0.containsKey("test.proto.errors"));
assertFalse(cache1.containsKey("test.proto.errors"));
assertFalse(cache0.containsKey(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX));
assertFalse(cache1.containsKey(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX));
assertNoTransactionsAndLocks();
}
public void testStatusAfterPutAll() {
Cache<String, String> cache0 = cache(0);
Cache<String, String> cache1 = cache(1);
assertTrue(cache0.isEmpty());
assertTrue(cache1.isEmpty());
String file1 = "import \"missing.proto\";";
String file2 = "package b;";
Map<String, String> map = new HashMap<>();
map.put("a.proto", file1);
map.put("b.proto", file2);
cache0.putAll(map);
assertEquals(file1, cache0.get("a.proto"));
assertEquals(file2, cache0.get("b.proto"));
assertEquals(file1, cache1.get("a.proto"));
assertEquals(file2, cache1.get("b.proto"));
assertEquals("Import 'missing.proto' not found", cache0.get("a.proto.errors"));
assertEquals("Import 'missing.proto' not found", cache1.get("a.proto.errors"));
assertFalse(cache0.containsKey("b.proto.errors"));
assertFalse(cache1.containsKey("b.proto.errors"));
assertTrue(cache0.containsKey(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX));
assertTrue(cache1.containsKey(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX));
assertEquals("a.proto", cache0.get(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX));
assertEquals("a.proto", cache1.get(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX));
file1 = "package a;";
map.put("a.proto", file1);
cache0.putAll(map);
assertEquals(file1, cache0.get("a.proto"));
assertEquals(file1, cache1.get("a.proto"));
assertEquals(file2, cache0.get("b.proto"));
assertEquals(file2, cache1.get("b.proto"));
assertFalse(cache0.containsKey("a.proto.errors"));
assertFalse(cache1.containsKey("a.proto.errors"));
assertFalse(cache0.containsKey("b.proto.errors"));
assertFalse(cache1.containsKey("b.proto.errors"));
assertFalse(cache0.containsKey(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX));
assertFalse(cache1.containsKey(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX));
assertNoTransactionsAndLocks();
}
public void testStatusAfterRemove() {
Cache<String, String> cache0 = cache(0);
Cache<String, String> cache1 = cache(1);
assertTrue(cache0.isEmpty());
assertTrue(cache1.isEmpty());
String value = "import \"missing.proto\";";
cache0.put("test.proto", value);
assertEquals(value, cache0.get("test.proto"));
assertEquals(value, cache1.get("test.proto"));
assertEquals("Import 'missing.proto' not found", cache0.get("test.proto.errors"));
assertEquals("Import 'missing.proto' not found", cache1.get("test.proto.errors"));
cache0.remove("test.proto");
assertFalse(cache0.containsKey("test.proto"));
assertFalse(cache1.containsKey("test.proto"));
assertFalse(cache0.containsKey("test.proto.errors"));
assertFalse(cache1.containsKey("test.proto.errors"));
assertFalse(cache0.containsKey(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX));
assertFalse(cache1.containsKey(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX));
assertNoTransactionsAndLocks();
}
public void testUnsupportedCommands() {
Cache<String, String> cache0 = cache(0);
assertTrue(cache0.isEmpty());
try {
cache0.compute("test.proto", (k, v) -> "import \"missing.proto\";");
} catch (Exception e) {
assertTrue(e instanceof CacheException);
assertTrue(e.getMessage().contains("ISPN028014"));
}
assertTrue(cache0.isEmpty());
try {
FunctionalMap.ReadWriteMap<String, String> rwMap = ReadWriteMapImpl.create(FunctionalMapImpl.create(cache0.getAdvancedCache()));
rwMap.eval("test.proto", "val", (value, view) -> {
view.set(value);
return "ret";
}).join();
} catch (CompletionException e) {
assertTrue(e.getCause() instanceof CacheException);
assertTrue(e.getCause().getMessage().contains("ISPN028014"));
}
assertTrue(cache0.isEmpty());
assertNoTransactionsAndLocks();
}
/**
* State transfer is interesting because StateConsumerImpl uses PutKeyValueCommand with InternalCacheEntry values,
* in order to preserve timestamps.
*/
public void testStateTransfer() {
cache(0).put("state.proto", "import \"test.proto\";");
EmbeddedCacheManager manager = addClusterEnabledCacheManager(makeCfg());
try {
Cache<Object, Object> cache = manager.getCache();
assertEquals("import \"test.proto\";", cache.get("state.proto"));
cache(0).remove("state.proto");
assertFalse(cache.containsKey("state.proto"));
} finally {
killMember(2);
}
}
private void assertNoTransactionsAndLocks() {
assertNoTransactions();
waitForNoLocks(cache(0));
waitForNoLocks(cache(1));
}
private void waitForNoLocks(Cache<?, ?> cache) {
LockManager lm = TestingUtil.extractLockManager(cache);
if (lm != null) {
eventually(() -> {
for (Object key : cache.keySet()) {
if (lm.isLocked(key)) {
return false;
}
}
return true;
});
}
}
}
| 13,574
| 38.692982
| 137
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/test/java/org/infinispan/query/remote/impl/indexing/TestDomainSCI.java
|
package org.infinispan.query.remote.impl.indexing;
import org.infinispan.protostream.FileDescriptorSource;
import org.infinispan.protostream.SerializationContext;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.protostream.sampledomain.marshallers.AccountMarshaller;
import org.infinispan.protostream.sampledomain.marshallers.AddressMarshaller;
import org.infinispan.protostream.sampledomain.marshallers.GenderMarshaller;
import org.infinispan.protostream.sampledomain.marshallers.LimitsMarshaller;
import org.infinispan.protostream.sampledomain.marshallers.TransactionMarshaller;
import org.infinispan.protostream.sampledomain.marshallers.UserMarshaller;
public class TestDomainSCI implements SerializationContextInitializer {
static final String PROTOBUF_RES = "sample_bank_account/bank.proto";
public static final TestDomainSCI INSTANCE = new TestDomainSCI();
private TestDomainSCI() {
}
@Override
public String getProtoFileName() {
return PROTOBUF_RES;
}
@Override
public String getProtoFile() {
return FileDescriptorSource.getResourceAsString(getClass(), "/" + PROTOBUF_RES);
}
@Override
public void registerSchema(SerializationContext serCtx) {
serCtx.registerProtoFiles(FileDescriptorSource.fromString(getProtoFileName(), getProtoFile()));
}
@Override
public void registerMarshallers(SerializationContext ctx) {
ctx.registerMarshaller(new UserMarshaller());
ctx.registerMarshaller(new GenderMarshaller());
ctx.registerMarshaller(new AddressMarshaller());
ctx.registerMarshaller(new AccountMarshaller());
ctx.registerMarshaller(new LimitsMarshaller());
ctx.registerMarshaller(new TransactionMarshaller());
}
}
| 1,766
| 38.266667
| 101
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/test/java/org/infinispan/query/remote/impl/indexing/ProtobufValueWrapperIndexingTest.java
|
package org.infinispan.query.remote.impl.indexing;
import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP;
import static org.testng.Assert.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import java.util.Collections;
import java.util.List;
import org.hibernate.search.engine.search.query.SearchQuery;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.protostream.sampledomain.Address;
import org.infinispan.protostream.sampledomain.User;
import org.infinispan.query.impl.ComponentRegistryUtils;
import org.infinispan.search.mapper.mapping.SearchMapping;
import org.infinispan.search.mapper.scope.SearchScope;
import org.infinispan.search.mapper.session.SearchSession;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.transaction.TransactionMode;
import org.testng.annotations.Test;
/**
* @author anistor@redhat.com
* @since 6.0
*/
@Test(groups = "functional", testName = "query.remote.impl.indexing.ProtobufValueWrapperIndexingTest")
public class ProtobufValueWrapperIndexingTest extends SingleCacheManagerTest {
protected EmbeddedCacheManager createCacheManager() throws Exception {
ConfigurationBuilder cfg = getDefaultStandaloneCacheConfig(true);
cfg.transaction().transactionMode(TransactionMode.TRANSACTIONAL)
.memory().encoding().value().mediaType(MediaType.APPLICATION_PROTOSTREAM_TYPE)
.indexing().enable()
.storage(LOCAL_HEAP)
.addIndexedEntity("sample_bank_account.User");
GlobalConfigurationBuilder globalBuilder = new GlobalConfigurationBuilder().nonClusteredDefault();
globalBuilder.serialization().addContextInitializer(TestDomainSCI.INSTANCE);
return TestCacheManagerFactory.createCacheManager(globalBuilder, cfg);
}
public void testIndexingWithWrapper() {
SearchMapping searchMapping = ComponentRegistryUtils.getSearchMapping(cache);
assertNotNull(searchMapping);
// Store some test data:
cache.put(new byte[]{1, 2, 3}, createUser("Adrian", "Nistor"));
cache.put(new byte[]{4, 5, 6}, createUser("John", "Batman"));
SearchSession session = searchMapping.getMappingSession();
SearchScope<byte[]> scope = session.scope(byte[].class, "sample_bank_account.User");
SearchQuery<Object> query = session.search(scope)
.select(f -> f.field("surname"))
.where(f -> f.match().field("name").matching("Adrian"))
.toQuery();
List<Object> result = query.fetchAllHits();
assertEquals(1, result.size());
assertEquals("Nistor", result.get(0));
}
private User createUser(String name, String surname) {
User user = new User();
user.setId(1);
user.setName(name);
user.setSurname(surname);
user.setGender(User.Gender.MALE);
user.setAccountIds(Collections.singleton(12));
Address address = new Address();
address.setStreet("Dark Alley");
address.setPostCode("1234");
user.setAddresses(Collections.singletonList(address));
return user;
}
}
| 3,341
| 40.259259
| 104
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/ProtobufMetadataManager.java
|
package org.infinispan.query.remote;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.protostream.BaseMarshaller;
import org.infinispan.query.remote.client.ProtobufMetadataManagerMBean;
/**
* A clustered persistent and replicated repository of protobuf definition files. All protobuf types and their
* marshallers must be registered with this repository before being used.
* <p>
* ProtobufMetadataManager is backed by an internal replicated cache named ___protobuf_metadata.
*
* @author anistor@redhat.com
* @since 8.0
*/
@Scope(Scopes.GLOBAL)
public interface ProtobufMetadataManager extends ProtobufMetadataManagerMBean {
/**
* @deprecated since 12.1. Will be removed in 15.0. Use the CREATE permission instead.
*/
@Deprecated
String SCHEMA_MANAGER_ROLE = "___schema_manager";
void registerMarshaller(BaseMarshaller<?> marshaller);
void unregisterMarshaller(BaseMarshaller<?> marshaller);
}
| 995
| 32.2
| 110
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/package-info.java
|
/**
* Server-side remote query components.
*
* @api.public-api
*/
package org.infinispan.query.remote;
| 107
| 14.428571
| 39
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/ProtobufMetadataManagerInterceptor.java
|
package org.infinispan.query.remote.impl;
import static org.infinispan.query.remote.client.ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX;
import static org.infinispan.query.remote.client.ProtobufMetadataManagerConstants.PROTO_KEY_SUFFIX;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.infinispan.commands.AbstractVisitor;
import org.infinispan.commands.CommandsFactory;
import org.infinispan.commands.FlagAffectedCommand;
import org.infinispan.commands.ReplicableCommand;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.commands.control.LockControlCommand;
import org.infinispan.commands.functional.ReadWriteKeyCommand;
import org.infinispan.commands.functional.ReadWriteKeyValueCommand;
import org.infinispan.commands.functional.ReadWriteManyCommand;
import org.infinispan.commands.functional.ReadWriteManyEntriesCommand;
import org.infinispan.commands.functional.WriteOnlyKeyCommand;
import org.infinispan.commands.functional.WriteOnlyKeyValueCommand;
import org.infinispan.commands.functional.WriteOnlyManyCommand;
import org.infinispan.commands.functional.WriteOnlyManyEntriesCommand;
import org.infinispan.commands.tx.PrepareCommand;
import org.infinispan.commands.write.ClearCommand;
import org.infinispan.commands.write.ComputeCommand;
import org.infinispan.commands.write.ComputeIfAbsentCommand;
import org.infinispan.commands.write.PutKeyValueCommand;
import org.infinispan.commands.write.PutMapCommand;
import org.infinispan.commands.write.RemoveCommand;
import org.infinispan.commands.write.ReplaceCommand;
import org.infinispan.commands.write.WriteCommand;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.context.impl.TxInvocationContext;
import org.infinispan.distribution.ch.KeyPartitioner;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.impl.ComponentRef;
import org.infinispan.interceptors.AsyncInterceptorChain;
import org.infinispan.interceptors.BaseCustomAsyncInterceptor;
import org.infinispan.interceptors.InvocationStage;
import org.infinispan.interceptors.SyncInvocationStage;
import org.infinispan.marshall.protostream.impl.SerializationContextRegistry;
import org.infinispan.metadata.EmbeddedMetadata;
import org.infinispan.metadata.Metadata;
import org.infinispan.protostream.DescriptorParserException;
import org.infinispan.protostream.FileDescriptorSource;
import org.infinispan.protostream.SerializationContext;
import org.infinispan.protostream.descriptors.FileDescriptor;
import org.infinispan.query.remote.ProtobufMetadataManager;
import org.infinispan.query.remote.client.ProtobufMetadataManagerConstants;
import org.infinispan.query.remote.impl.logging.Log;
import org.infinispan.util.KeyValuePair;
/**
* Intercepts updates to the protobuf schema file caches and updates the SerializationContext accordingly.
*
* <p>Must be in the interceptor chain after {@code EntryWrappingInterceptor} so that it can fail a write after
* {@code CallInterceptor} updates the context entry but before {@code EntryWrappingInterceptor} commits the entry.</p>
*
* @author anistor@redhat.com
* @since 7.0
*/
final class ProtobufMetadataManagerInterceptor extends BaseCustomAsyncInterceptor {
private static final Log log = LogFactory.getLog(ProtobufMetadataManagerInterceptor.class, Log.class);
private static final Metadata DEFAULT_METADATA = new EmbeddedMetadata.Builder().build();
private CommandsFactory commandsFactory;
private ComponentRef<AsyncInterceptorChain> invoker;
private SerializationContext serializationContext;
private KeyPartitioner keyPartitioner;
private SerializationContextRegistry serializationContextRegistry;
/**
* A no-op callback.
*/
private static final FileDescriptorSource.ProgressCallback EMPTY_CALLBACK = new FileDescriptorSource.ProgressCallback() {
};
private final static class ProgressCallback implements FileDescriptorSource.ProgressCallback {
private final Map<String, DescriptorParserException> errorFiles = new TreeMap<>();
private final Set<String> successFiles = new TreeSet<>();
Map<String, DescriptorParserException> getErrorFiles() {
return errorFiles;
}
public Set<String> getSuccessFiles() {
return successFiles;
}
@Override
public void handleError(String fileName, DescriptorParserException exception) {
// handle first error per file, ignore the rest if any
errorFiles.putIfAbsent(fileName, exception);
}
@Override
public void handleSuccess(String fileName) {
// a file that is already failed cannot be added as success
if (!errorFiles.containsKey(fileName)) {
successFiles.add(fileName);
}
}
}
/**
* Visitor used for handling the list of modifications of a PrepareCommand.
*/
private final AbstractVisitor serializationContextUpdaterVisitor = new AbstractVisitor() {
@Override
public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) {
final String key = (String) command.getKey();
if (shouldIntercept(key)) {
registerProtoFile(key, (String) command.getValue(), EMPTY_CALLBACK);
}
return null;
}
@Override
public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) {
final Map<Object, Object> map = command.getMap();
FileDescriptorSource source = new FileDescriptorSource().withProgressCallback(EMPTY_CALLBACK);
for (Object key : map.keySet()) {
if (shouldIntercept(key)) {
source.addProtoFile((String) key, (String) map.get(key));
}
}
registerFileDescriptorSource(source, source.getFiles().keySet().toString());
return null;
}
@Override
public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) {
final String key = (String) command.getKey();
if (shouldIntercept(key)) {
registerProtoFile(key, (String) command.getNewValue(), EMPTY_CALLBACK);
}
return null;
}
@Override
public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) {
final String key = (String) command.getKey();
if (shouldIntercept(key)) {
if (serializationContext.getFileDescriptors().containsKey(key)) {
serializationContext.unregisterProtoFile(key);
}
}
return null;
}
@Override
public Object visitClearCommand(InvocationContext ctx, ClearCommand command) {
for (String fileName : serializationContext.getFileDescriptors().keySet()) {
serializationContext.unregisterProtoFile(fileName);
}
return null;
}
};
private void registerProtoFile(String name, String content, FileDescriptorSource.ProgressCallback callback) {
FileDescriptorSource source = new FileDescriptorSource()
.withProgressCallback(callback)
.addProtoFile(name, content);
registerFileDescriptorSource(source, source.getFiles().keySet().toString());
}
@Inject
public void init(CommandsFactory commandsFactory, ComponentRef<AsyncInterceptorChain> invoker, KeyPartitioner keyPartitioner,
ProtobufMetadataManager protobufMetadataManager, SerializationContextRegistry serializationContextRegistry) {
this.commandsFactory = commandsFactory;
this.invoker = invoker;
this.keyPartitioner = keyPartitioner;
this.serializationContext = ((ProtobufMetadataManagerImpl) protobufMetadataManager).getSerializationContext();
this.serializationContextRegistry = serializationContextRegistry;
}
@Override
public Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) {
return invokeNextThenAccept(ctx, command, (rCtx, rCommand, rv) -> {
if (!rCtx.isOriginLocal()) {
// apply updates to the serialization context
for (WriteCommand wc : rCommand.getModifications()) {
wc.acceptVisitor(rCtx, serializationContextUpdaterVisitor);
}
}
});
}
@Override
public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) {
final Object key = command.getKey();
if (!(key instanceof String)) {
throw log.keyMustBeString(key.getClass());
}
if (!shouldIntercept(key)) {
return invokeNext(ctx, command);
}
InvocationStage stage;
if (ctx.isOriginLocal() && !command.hasAnyFlag(FlagBitSets.PUT_FOR_STATE_TRANSFER | FlagBitSets.SKIP_LOCKING)) {
if (!((String) key).endsWith(PROTO_KEY_SUFFIX)) {
throw log.keyMustBeStringEndingWithProto(key);
}
// lock global errors key
LockControlCommand cmd = commandsFactory.buildLockControlCommand(ERRORS_KEY_SUFFIX, command.getFlagsBitSet(), null);
stage = invoker.running().invokeStage(ctx, cmd);
} else {
stage = SyncInvocationStage.completedNullStage();
}
return makeStage(asyncInvokeNext(ctx, command, stage))
.thenApply(ctx, command, this::handlePutKeyValueResult);
}
private InvocationStage handlePutKeyValueResult(InvocationContext ctx, PutKeyValueCommand putKeyValueCommand, Object rv) {
if (putKeyValueCommand.isSuccessful()) {
// StateConsumerImpl uses PutKeyValueCommands with InternalCacheEntry
// values in order to preserve timestamps, so read the value from the context
Object key = putKeyValueCommand.getKey();
Object value = ctx.lookupEntry(key).getValue();
if (!(value instanceof String)) {
throw log.valueMustBeString(value.getClass());
}
long flagsBitSet = copyFlags(putKeyValueCommand);
if (ctx.isOriginLocal() && !putKeyValueCommand.hasAnyFlag(FlagBitSets.PUT_FOR_STATE_TRANSFER)) {
ProgressCallback progressCallback = new ProgressCallback();
registerProtoFile((String) key, (String) value, progressCallback);
List<KeyValuePair<String, String>> errorUpdates = computeErrorUpdates(progressCallback);
InvocationStage updateStage = updateSchemaErrorsIterator(ctx, flagsBitSet, errorUpdates.iterator());
return makeStage(updateStage.thenReturn(ctx, putKeyValueCommand, rv));
}
registerProtoFile((String) key, (String) value, EMPTY_CALLBACK);
}
return makeStage(rv);
}
List<KeyValuePair<String, String>> computeErrorUpdates(ProgressCallback progressCallback) {
// List of updated proto schemas and their errors
// Proto schemas with no errors have a null value
List<KeyValuePair<String, String>> errorUpdates = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, DescriptorParserException> errorEntry : progressCallback.getErrorFiles().entrySet()) {
String fdName = errorEntry.getKey();
String errorValue = errorEntry.getValue().getMessage();
if (sb.length() > 0) {
sb.append('\n');
}
sb.append(fdName);
errorUpdates.add(KeyValuePair.of(fdName, errorValue));
}
for (String successKeyName : progressCallback.getSuccessFiles()) {
errorUpdates.add(KeyValuePair.of(successKeyName, null));
}
errorUpdates.add(KeyValuePair.of("", sb.length() > 0 ? sb.toString() : null));
return errorUpdates;
}
/**
* For preload, we need to copy the CACHE_MODE_LOCAL flag from the put command.
* But we also need to remove the SKIP_CACHE_STORE flag, so that existing .errors keys are updated.
*/
private long copyFlags(FlagAffectedCommand command) {
return command.getFlagsBitSet() | FlagBitSets.IGNORE_RETURN_VALUES & ~FlagBitSets.SKIP_CACHE_STORE;
}
@Override
public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) {
if (!ctx.isOriginLocal()) {
return invokeNext(ctx, command);
}
final Map<Object, Object> map = command.getMap();
FileDescriptorSource source = new FileDescriptorSource();
for (Object key : map.keySet()) {
final Object value = map.get(key);
if (!(key instanceof String)) {
throw log.keyMustBeString(key.getClass());
}
if (!(value instanceof String)) {
throw log.valueMustBeString(value.getClass());
}
if (shouldIntercept(key)) {
if (!((String) key).endsWith(PROTO_KEY_SUFFIX)) {
throw log.keyMustBeStringEndingWithProto(key);
}
source.addProtoFile((String) key, (String) value);
}
}
// lock global errors key
VisitableCommand cmd = commandsFactory.buildLockControlCommand(ERRORS_KEY_SUFFIX, command.getFlagsBitSet(), null);
InvocationStage stage = invoker.running().invokeStage(ctx, cmd);
return makeStage(asyncInvokeNext(ctx, command, stage)).thenApply(ctx, command, (rCtx, rCommand, rv) -> {
long flagsBitSet = copyFlags(rCommand);
ProgressCallback progressCallback = null;
if (rCtx.isOriginLocal()) {
progressCallback = new ProgressCallback();
source.withProgressCallback(progressCallback);
} else {
source.withProgressCallback(EMPTY_CALLBACK);
}
registerFileDescriptorSource(source, source.getFiles().keySet().toString());
if (progressCallback != null) {
List<KeyValuePair<String, String>> errorUpdates = computeErrorUpdates(progressCallback);
return updateSchemaErrorsIterator(rCtx, flagsBitSet, errorUpdates.iterator());
}
return InvocationStage.completedNullStage();
});
}
private void registerFileDescriptorSource(FileDescriptorSource source, String fileNameString) {
try {
// Register protoFiles with remote-query context
serializationContext.registerProtoFiles(source);
// Register schema with user context to allow transcoding
serializationContextRegistry.addProtoFile(SerializationContextRegistry.MarshallerType.USER, source);
} catch (DescriptorParserException e) {
throw log.failedToParseProtoFile(fileNameString, e);
}
}
@Override
public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) {
if (!ctx.isOriginLocal()) {
return invokeNext(ctx, command);
}
if (!(command.getKey() instanceof String)) {
throw log.keyMustBeString(command.getKey().getClass());
}
String key = (String) command.getKey();
if (!shouldIntercept(key)) {
return invokeNext(ctx, command);
}
// lock global errors key
long flagsBitSet = copyFlags(command);
LockControlCommand lockCommand = commandsFactory.buildLockControlCommand(ERRORS_KEY_SUFFIX, flagsBitSet, null);
InvocationStage stage = invoker.running().invokeStage(ctx, lockCommand);
stage = stage.thenApplyMakeStage(ctx, command, (rCtx, rCommand, __) -> {
if (serializationContext.getFileDescriptors().containsKey(key)) {
serializationContext.unregisterProtoFile(key);
}
if (serializationContextRegistry.getUserCtx().getFileDescriptors().containsKey(key)) {
serializationContextRegistry.removeProtoFile(SerializationContextRegistry.MarshallerType.USER, key);
}
// put error key for all unresolved files and remove error key for all resolved files
// Error keys to be removed have a null value
List<KeyValuePair<String, String>> errorUpdates = computeErrorUpdatesAfterRemove(key);
return updateSchemaErrorsIterator(rCtx, flagsBitSet, errorUpdates.iterator());
});
return asyncInvokeNext(ctx, command, stage);
}
private List<KeyValuePair<String, String>> computeErrorUpdatesAfterRemove(String key) {
// List of proto schemas and their errors
// Proto schemas with no errors have a null value
List<KeyValuePair<String, String>> errorUpdates = new ArrayList<>();
errorUpdates.add(KeyValuePair.of(key, null));
StringBuilder sb = new StringBuilder();
for (FileDescriptor fd : serializationContext.getFileDescriptors().values()) {
String fdName = fd.getName();
if (fd.isResolved()) {
errorUpdates.add(KeyValuePair.of(fdName, null));
} else {
if (sb.length() > 0) {
sb.append('\n');
}
sb.append(fdName);
errorUpdates.add(KeyValuePair.of(fdName, "One of the imported files is missing or has errors"));
}
}
errorUpdates.add(KeyValuePair.of("", sb.length() > 0 ? sb.toString() : null));
return errorUpdates;
}
private InvocationStage updateSchemaErrorsIterator(InvocationContext ctx, long flagsBitSet,
Iterator<KeyValuePair<String, String>> iterator) {
if (!iterator.hasNext())
return InvocationStage.completedNullStage();
KeyValuePair<String, String> keyErrorPair = iterator.next();
Object errorsKey = keyErrorPair.getKey() + ERRORS_KEY_SUFFIX;
String errorsValue = keyErrorPair.getValue();
int segment = keyPartitioner.getSegment(errorsKey);
WriteCommand writeCommand;
if (errorsValue == null) {
writeCommand = commandsFactory.buildRemoveCommand(errorsKey, null, segment, flagsBitSet);
} else {
PutKeyValueCommand put = commandsFactory.buildPutKeyValueCommand(errorsKey, errorsValue, segment,
DEFAULT_METADATA, flagsBitSet);
put.setPutIfAbsent(true);
writeCommand = put;
}
InvocationStage stage = invoker.running().invokeStage(ctx, writeCommand);
return stage.thenApplyMakeStage(ctx, writeCommand, (rCtx, rCommand, rv) -> updateSchemaErrorsIterator(rCtx, flagsBitSet, iterator));
}
@Override
public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) {
final Object key = command.getKey();
final Object value = command.getNewValue();
if (!ctx.isOriginLocal()) {
return invokeNext(ctx, command);
}
if (!(key instanceof String)) {
throw log.keyMustBeString(key.getClass());
}
if (!(value instanceof String)) {
throw log.valueMustBeString(value.getClass());
}
if (!shouldIntercept(key)) {
return invokeNext(ctx, command);
}
if (!((String) key).endsWith(PROTO_KEY_SUFFIX)) {
throw log.keyMustBeStringEndingWithProto(key);
}
// lock global errors key
LockControlCommand cmd = commandsFactory.buildLockControlCommand(ERRORS_KEY_SUFFIX, command.getFlagsBitSet(),
null);
InvocationStage stage = invoker.running().invokeStage(ctx, cmd);
return makeStage(asyncInvokeNext(ctx, command, stage)).thenApply(ctx, command, (rCtx, rCommand, rv) -> {
if (rCommand.isSuccessful()) {
long flagsBitSet = copyFlags(rCommand);
if (rCtx.isOriginLocal()) {
ProgressCallback progressCallback = new ProgressCallback();
registerProtoFile((String) key, (String) value, progressCallback);
List<KeyValuePair<String, String>> errorUpdates = computeErrorUpdates(progressCallback);
return updateSchemaErrorsIterator(rCtx, flagsBitSet, errorUpdates.iterator());
}
registerProtoFile((String) key, (String) value, EMPTY_CALLBACK);
}
return InvocationStage.completedNullStage();
});
}
@Override
public Object visitClearCommand(InvocationContext ctx, ClearCommand command) {
for (String fileName : serializationContext.getFileDescriptors().keySet()) {
serializationContext.unregisterProtoFile(fileName);
}
return invokeNext(ctx, command);
}
private boolean shouldIntercept(Object key) {
return !((String) key).endsWith(ERRORS_KEY_SUFFIX);
}
// --- unsupported operations: compute, computeIfAbsent, eval or any other functional map commands ---
@Override
public Object visitComputeCommand(InvocationContext ctx, ComputeCommand command) {
return handleUnsupportedCommand(command);
}
@Override
public Object visitComputeIfAbsentCommand(InvocationContext ctx, ComputeIfAbsentCommand command) {
return handleUnsupportedCommand(command);
}
@Override
public Object visitWriteOnlyKeyCommand(InvocationContext ctx, WriteOnlyKeyCommand command) {
return handleUnsupportedCommand(command);
}
@Override
public Object visitWriteOnlyKeyValueCommand(InvocationContext ctx, WriteOnlyKeyValueCommand command) {
return handleUnsupportedCommand(command);
}
@Override
public Object visitWriteOnlyManyCommand(InvocationContext ctx, WriteOnlyManyCommand command) {
return handleUnsupportedCommand(command);
}
@Override
public Object visitWriteOnlyManyEntriesCommand(InvocationContext ctx, WriteOnlyManyEntriesCommand command) {
return handleUnsupportedCommand(command);
}
@Override
public Object visitReadWriteKeyCommand(InvocationContext ctx, ReadWriteKeyCommand command) {
return handleUnsupportedCommand(command);
}
@Override
public Object visitReadWriteKeyValueCommand(InvocationContext ctx, ReadWriteKeyValueCommand command) {
return handleUnsupportedCommand(command);
}
@Override
public Object visitReadWriteManyCommand(InvocationContext ctx, ReadWriteManyCommand command) {
return handleUnsupportedCommand(command);
}
@Override
public Object visitReadWriteManyEntriesCommand(InvocationContext ctx, ReadWriteManyEntriesCommand command) {
return handleUnsupportedCommand(command);
}
private Object handleUnsupportedCommand(ReplicableCommand command) {
throw log.cacheDoesNotSupportCommand(ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME, command.getClass().getName());
}
}
| 22,571
| 41.11194
| 138
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/ObjectRemoteQueryManager.java
|
package org.infinispan.query.remote.impl;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_PROTOSTREAM;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.infinispan.AdvancedCache;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.factories.impl.BasicComponentRegistry;
import org.infinispan.objectfilter.Matcher;
import org.infinispan.objectfilter.impl.ReflectionMatcher;
import org.infinispan.objectfilter.impl.syntax.parser.EntityNameResolver;
import org.infinispan.objectfilter.impl.syntax.parser.ReflectionEntityNamesResolver;
import org.infinispan.protostream.SerializationContext;
import org.infinispan.query.backend.QueryInterceptor;
import org.infinispan.query.dsl.embedded.impl.ObjectReflectionMatcher;
import org.infinispan.search.mapper.mapping.SearchMapping;
/**
* Implementation of {@link RemoteQueryManager} for caches storing deserialized content (Java Objects).
*
* @since 9.4
*/
final class ObjectRemoteQueryManager extends BaseRemoteQueryManager {
private final Map<String, ObjectRemoteQueryEngine> enginePerMediaType = new ConcurrentHashMap<>();
private final SerializationContext serCtx;
private final SearchMapping searchMapping;
private final ComponentRegistry cr;
ObjectRemoteQueryManager(AdvancedCache<?, ?> cache, ComponentRegistry cr, QuerySerializers querySerializers) {
super(cache, querySerializers, cr);
this.cr = cr;
this.searchMapping = cr.getComponent(SearchMapping.class);
this.serCtx = SecurityActions.getSerializationContext(cache.getCacheManager());
BasicComponentRegistry bcr = cr.getComponent(BasicComponentRegistry.class);
ObjectReflectionMatcher objectReflectionMatcher = ObjectReflectionMatcher.create(cache,
createEntityNamesResolver(APPLICATION_OBJECT), searchMapping);
bcr.replaceComponent(ObjectReflectionMatcher.class.getName(), objectReflectionMatcher, true);
bcr.rewire();
ProtobufObjectReflectionMatcher protobufObjectReflectionMatcher = ProtobufObjectReflectionMatcher.create(createEntityNamesResolver(APPLICATION_PROTOSTREAM), serCtx);
bcr.registerComponent(ProtobufObjectReflectionMatcher.class, protobufObjectReflectionMatcher, true);
}
@Override
public Class<? extends Matcher> getMatcherClass(MediaType mediaType) {
return getQueryEngineForMediaType(mediaType).getMatcherClass();
}
@Override
public ObjectRemoteQueryEngine getQueryEngine(AdvancedCache<?, ?> cache) {
return getQueryEngineForMediaType(cache.getValueDataConversion().getRequestMediaType());
}
@Override
public Object encodeFilterResult(Object filterResult) {
return filterResult;
}
private ObjectRemoteQueryEngine getQueryEngineForMediaType(MediaType mediaType) {
ObjectRemoteQueryEngine queryEngine = enginePerMediaType.get(mediaType.getTypeSubtype());
if (queryEngine == null) {
ReflectionMatcher matcher = mediaType.match(APPLICATION_PROTOSTREAM) ? cr.getComponent(ProtobufObjectReflectionMatcher.class) :
cr.getComponent(ObjectReflectionMatcher.class);
queryEngine = new ObjectRemoteQueryEngine(cache, searchMapping != null, matcher.getClass());
enginePerMediaType.put(mediaType.getTypeSubtype(), queryEngine);
}
return queryEngine;
}
private EntityNameResolver<Class<?>> createEntityNamesResolver(MediaType mediaType) {
if (mediaType.match(APPLICATION_PROTOSTREAM)) {
return new ProtobufEntityNameResolver(serCtx);
} else {
ClassLoader classLoader = cr.getGlobalComponentRegistry().getComponent(ClassLoader.class);
ReflectionEntityNamesResolver reflectionEntityNamesResolver = new ReflectionEntityNamesResolver(classLoader);
if (searchMapping != null) {
// If indexing is enabled then use the declared set of indexed classes for lookup but fallback to global classloader.
QueryInterceptor queryInterceptor = cr.getComponent(QueryInterceptor.class);
Map<String, Class<?>> indexedEntities = queryInterceptor.indexedEntities();
return name -> {
Class<?> c = indexedEntities.get(name);
if (c == null) {
c = reflectionEntityNamesResolver.resolve(name);
}
return c;
};
}
return reflectionEntityNamesResolver;
}
}
}
| 4,595
| 44.058824
| 171
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/package-info.java
|
/**
* @api.private
*/
package org.infinispan.query.remote.impl;
| 66
| 12.4
| 41
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/ExternalizerIds.java
|
package org.infinispan.query.remote.impl;
/**
* Identifiers used by the Marshaller to delegate to specialized Externalizers. For details, read
* http://infinispan.org/docs/9.0.x/user_guide/user_guide.html#_preassigned_externalizer_id_ranges
* <p/>
* The range reserved for the Infinispan Remote Query module is from 1700 to 1799.
*
* @author anistor@redhat.com
* @since 6.0
*/
public interface ExternalizerIds {
Integer PROTOBUF_VALUE_WRAPPER = 1700;
Integer ICKLE_PROTOBUF_CACHE_EVENT_FILTER_CONVERTER = 1701;
Integer ICKLE_PROTOBUF_FILTER_AND_CONVERTER = 1702;
Integer ICKLE_CONTINUOUS_QUERY_CACHE_EVENT_FILTER_CONVERTER = 1703;
Integer ICKLE_BINARY_PROTOBUF_FILTER_AND_CONVERTER = 1704;
Integer ICKLE_CONTINUOUS_QUERY_RESULT = 1705;
Integer ICKLE_FILTER_RESULT = 1706;
}
| 811
| 28
| 98
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/QuerySerializers.java
|
package org.infinispan.query.remote.impl;
import java.util.concurrent.ConcurrentHashMap;
import org.infinispan.commons.dataconversion.MediaType;
final class QuerySerializers {
private final ConcurrentHashMap<String, QuerySerializer<?>> serializers = new ConcurrentHashMap<>(2);
QuerySerializers() {
}
void addSerializer(MediaType mediaType, QuerySerializer<?> querySerializer) {
serializers.put(mediaType.getTypeSubtype(), querySerializer);
}
QuerySerializer<?> getSerializer(MediaType requestMediaType) {
QuerySerializer<?> querySerializer = serializers.get(requestMediaType.getTypeSubtype());
if (querySerializer != null) return querySerializer;
return serializers.get(MediaType.MATCH_ALL_TYPE);
}
}
| 755
| 29.24
| 104
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/DefaultQuerySerializer.java
|
package org.infinispan.query.remote.impl;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_PROTOSTREAM;
import static org.infinispan.query.remote.impl.RemoteQueryManager.PROTOSTREAM_UNWRAPPED;
import static org.infinispan.query.remote.impl.RemoteQueryManager.QUERY_REQUEST_TYPE;
import java.util.ArrayList;
import java.util.List;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.dataconversion.Transcoder;
import org.infinispan.marshall.core.EncoderRegistry;
import org.infinispan.protostream.WrappedMessage;
import org.infinispan.query.remote.client.impl.QueryRequest;
import org.infinispan.query.remote.client.impl.QueryResponse;
/**
* Handles serialization of Query results in marshalled {@link QueryResponse} format.
*
* @since 9.4
*/
class DefaultQuerySerializer implements QuerySerializer<QueryResponse> {
private final EncoderRegistry encoderRegistry;
DefaultQuerySerializer(EncoderRegistry encoderRegistry) {
this.encoderRegistry = encoderRegistry;
}
@Override
public QueryRequest decodeQueryRequest(byte[] queryRequest, MediaType mediaType) {
// QueryRequests are sent in 'unwrapped' protobuf format
if (mediaType.match(APPLICATION_PROTOSTREAM)) mediaType = PROTOSTREAM_UNWRAPPED;
Transcoder transcoder = encoderRegistry.getTranscoder(APPLICATION_OBJECT, mediaType);
return (QueryRequest) transcoder.transcode(queryRequest, mediaType, QUERY_REQUEST_TYPE);
}
@Override
public QueryResponse createQueryResponse(RemoteQueryResult remoteQueryResult) {
List<?> list = remoteQueryResult.getResults();
int numResults = list.size();
String[] projection = remoteQueryResult.getProjections();
int projSize = projection != null ? projection.length : 0;
List<WrappedMessage> results = new ArrayList<>(projSize == 0 ? numResults : numResults * projSize);
for (Object o : list) {
if (projSize == 0) {
results.add(new WrappedMessage(o));
} else {
Object[] row = (Object[]) o;
for (int i = 0; i < projSize; i++) {
results.add(new WrappedMessage(row[i]));
}
}
}
QueryResponse response = new QueryResponse();
response.hitCount(remoteQueryResult.hitCount());
response.hitCountExact(remoteQueryResult.hitCountExact());
response.setNumResults(numResults);
response.setProjectionSize(projSize);
response.setResults(results);
return response;
}
public byte[] encodeQueryResponse(Object queryResponse, MediaType destinationType) {
MediaType destination = destinationType;
// QueryResponses are sent in 'unwrapped' protobuf format
if (destinationType.match(APPLICATION_PROTOSTREAM)) destination = PROTOSTREAM_UNWRAPPED;
Transcoder transcoder = encoderRegistry.getTranscoder(APPLICATION_OBJECT, destinationType);
return (byte[]) transcoder.transcode(queryResponse, APPLICATION_OBJECT, destination);
}
}
| 3,114
| 39.454545
| 105
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/SecurityActions.java
|
package org.infinispan.query.remote.impl;
import static org.infinispan.security.Security.doPrivileged;
import org.infinispan.AdvancedCache;
import org.infinispan.Cache;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.protostream.SerializationContext;
import org.infinispan.security.AuthorizationManager;
import org.infinispan.security.impl.SecureCacheImpl;
/**
* SecurityActions for the org.infinispan.query.remote.impl package. Do not move and do not change class and method
* visibility!
*
* @author anistor@redhat.com
* @since 7.2
*/
final class SecurityActions {
static RemoteQueryManager getRemoteQueryManager(AdvancedCache<?, ?> cache) {
return org.infinispan.security.actions.SecurityActions.getCacheComponentRegistry(cache).getComponent(RemoteQueryManager.class);
}
static AuthorizationManager getCacheAuthorizationManager(AdvancedCache<?, ?> cache) {
return doPrivileged(cache::getAuthorizationManager);
}
static <K, V> Cache<K, V> getUnwrappedCache(EmbeddedCacheManager cacheManager, String cacheName) {
return doPrivileged(() -> {
Cache<K, V> cache = cacheManager.getCache(cacheName);
if (cache instanceof SecureCacheImpl) {
return ((SecureCacheImpl) cache).getDelegate();
} else {
return cache;
}
});
}
static SerializationContext getSerializationContext(EmbeddedCacheManager cacheManager) {
return doPrivileged(new GetSerializationContextAction(cacheManager));
}
}
| 1,531
| 33.818182
| 133
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/GetSerializationContextAction.java
|
package org.infinispan.query.remote.impl;
import java.util.function.Supplier;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.protostream.SerializationContext;
/**
* @author Dan Berindei
* @since 10.0
*/
public final class GetSerializationContextAction implements Supplier<SerializationContext> {
private final EmbeddedCacheManager cacheManager;
public GetSerializationContextAction(EmbeddedCacheManager cacheManager) {
this.cacheManager = cacheManager;
}
@Override
public SerializationContext get() {
return ProtobufMetadataManagerImpl.getSerializationContext(cacheManager);
}
}
| 645
| 24.84
| 92
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/ProtobufMetadataProjectableAdapter.java
|
package org.infinispan.query.remote.impl;
import org.infinispan.AdvancedCache;
import org.infinispan.container.entries.CacheEntry;
import org.infinispan.container.versioning.EntryVersion;
import org.infinispan.container.versioning.NumericVersion;
import org.infinispan.container.versioning.SimpleClusteredVersion;
import org.infinispan.metadata.Metadata;
import org.infinispan.objectfilter.impl.MetadataAdapter;
import org.infinispan.objectfilter.impl.syntax.parser.ProtobufPropertyHelper;
import org.infinispan.protostream.WrappedMessage;
import org.infinispan.protostream.descriptors.Descriptor;
import org.infinispan.protostream.descriptors.FieldDescriptor;
import org.infinispan.query.dsl.embedded.impl.MetadataProjectableAdapter;
public class ProtobufMetadataProjectableAdapter extends MetadataProjectableAdapter<Descriptor, FieldDescriptor, Integer> {
public ProtobufMetadataProjectableAdapter(MetadataAdapter<Descriptor, FieldDescriptor, Integer> baseAdapter, AdvancedCache<?, ?> cache) {
super(baseAdapter, cache);
}
@Override
public Object projection(CacheEntry<?, ?> cacheEntry, Integer attribute) {
if (ProtobufPropertyHelper.VALUE_FIELD_ATTRIBUTE_ID == attribute) {
return new WrappedMessage(cacheEntry.getValue());
}
Metadata metadata = cacheEntry.getMetadata();
if (attribute.equals(ProtobufPropertyHelper.VERSION_FIELD_ATTRIBUTE_ID)) {
EntryVersion version = metadata.version();
if (version instanceof NumericVersion) {
return ((NumericVersion) version).getVersion();
}
if (version instanceof SimpleClusteredVersion) {
return ((SimpleClusteredVersion) version).getVersion();
}
}
return null;
}
}
| 1,751
| 41.731707
| 140
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/RemoteQueryManager.java
|
package org.infinispan.query.remote.impl;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_PROTOSTREAM;
import static org.infinispan.encoding.ProtostreamTranscoder.WRAPPED_PARAM;
import java.util.Map;
import org.infinispan.AdvancedCache;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.encoding.DataConversion;
import org.infinispan.objectfilter.Matcher;
import org.infinispan.query.remote.client.FilterResult;
import org.infinispan.query.remote.client.impl.QueryRequest;
/**
* Manages components used during indexed and index-less query.
*
* @since 9.2
*/
public interface RemoteQueryManager {
MediaType PROTOSTREAM_UNWRAPPED = APPLICATION_PROTOSTREAM.withParameter(WRAPPED_PARAM, "false");
MediaType QUERY_REQUEST_TYPE = APPLICATION_OBJECT.withClassType(QueryRequest.class);
/**
* @return {@link Matcher} to be used during non-indexed query and filter operations.
*/
Class<? extends Matcher> getMatcherClass(MediaType mediaType);
/**
* @return {@link ObjectRemoteQueryEngine}
*/
ObjectRemoteQueryEngine getQueryEngine(AdvancedCache<?, ?> cache);
/**
* @param queryRequest serialized {@link QueryRequest} provided by the remote client.
* @return decoded {@link QueryRequest}.
*/
QueryRequest decodeQueryRequest(byte[] queryRequest, MediaType requestType);
/**
* @param filterResult the {@link FilterResult} from filtering and continuous query operations.
* @return Encoded FilterResult to send to the remote client.
*/
Object encodeFilterResult(Object filterResult);
Object convertKey(Object key, MediaType destinationFormat);
Object convertValue(Object value, MediaType destinationFormat);
DataConversion getKeyDataConversion();
DataConversion getValueDataConversion();
byte[] executeQuery(String queryString, Map<String, Object> namedParametersMap, Integer offset, Integer maxResults,
Integer hitCountAccuracy, AdvancedCache<?, ?> cache, MediaType outputFormat, boolean isLocal);
}
| 2,148
| 35.423729
| 118
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/LazySearchMapping.java
|
package org.infinispan.query.remote.impl;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_PROTOSTREAM;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.locks.StampedLock;
import org.hibernate.search.engine.common.spi.SearchIntegration;
import org.hibernate.search.engine.reporting.FailureHandler;
import org.infinispan.AdvancedCache;
import org.infinispan.Cache;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.configuration.cache.IndexingConfiguration;
import org.infinispan.encoding.DataConversion;
import org.infinispan.protostream.SerializationContext;
import org.infinispan.query.core.impl.QueryCache;
import org.infinispan.query.impl.EntityLoader;
import org.infinispan.query.remote.impl.logging.Log;
import org.infinispan.query.remote.impl.mapping.SerializationContextSearchMapping;
import org.infinispan.query.remote.impl.util.LazyRef;
import org.infinispan.search.mapper.mapping.SearchIndexedEntity;
import org.infinispan.search.mapper.mapping.SearchMapping;
import org.infinispan.search.mapper.mapping.SearchMappingBuilder;
import org.infinispan.search.mapper.mapping.SearchMappingCommonBuilding;
import org.infinispan.search.mapper.mapping.metamodel.IndexMetamodel;
import org.infinispan.search.mapper.mapping.impl.InfinispanMapping;
import org.infinispan.search.mapper.scope.SearchScope;
import org.infinispan.search.mapper.session.SearchSession;
import org.infinispan.search.mapper.work.SearchIndexer;
/**
* @since 12.0
*/
public class LazySearchMapping implements SearchMapping {
private static final Log log = LogFactory.getLog(LazySearchMapping.class, Log.class);
private final Cache<?, ?> cache;
private final ProtobufMetadataManagerImpl protobufMetadataManager;
private final SearchMappingCommonBuilding commonBuilding;
private final EntityLoader<?> entityLoader;
private final SerializationContext serCtx;
private final QueryCache queryCache;
private LazyRef<SearchMapping> searchMappingRef = new LazyRef<>(this::createMapping);
private final StampedLock stampedLock = new StampedLock();
private volatile boolean restarting = false;
public LazySearchMapping(SearchMappingCommonBuilding commonBuilding, EntityLoader<?> entityLoader,
SerializationContext serCtx, AdvancedCache<?, ?> cache,
ProtobufMetadataManagerImpl protobufMetadataManager, QueryCache queryCache) {
this.commonBuilding = commonBuilding;
this.entityLoader = entityLoader;
this.serCtx = serCtx;
this.cache = cache;
this.protobufMetadataManager = protobufMetadataManager;
this.queryCache = queryCache;
}
@Override
public <E> SearchScope<E> scope(Collection<? extends Class<? extends E>> types) {
return mapping().scope(types);
}
@Override
public SearchScope<?> scopeAll() {
return mapping().scopeAll();
}
@Override
public FailureHandler getFailureHandler() {
return mapping().getFailureHandler();
}
@Override
public void close() {
mapping().close();
}
@Override
public boolean isClose() {
return mapping().isClose();
}
@Override
public boolean isRestarting() {
return restarting;
}
@Override
public SearchSession getMappingSession() {
return mapping().getMappingSession();
}
@Override
public SearchIndexer getSearchIndexer() {
return mapping().getSearchIndexer();
}
@Override
public SearchIndexedEntity indexedEntity(Class<?> entityType) {
return mapping().indexedEntity(entityType);
}
@Override
public SearchIndexedEntity indexedEntity(String entityName) {
return mapping().indexedEntity(entityName);
}
@Override
public Collection<? extends SearchIndexedEntity> allIndexedEntities() {
return mapping().allIndexedEntities();
}
@Override
public Collection<? extends SearchIndexedEntity> indexedEntitiesForStatistics() {
long stamp = stampedLock.tryReadLock();
if (stamp == 0L) {
return Collections.emptySet();
}
try {
if (!searchMappingRef.available()) {
return Collections.emptySet();
}
return allIndexedEntities();
} finally {
stampedLock.unlockRead(stamp);
}
}
@Override
public Set<String> allIndexedEntityNames() {
return mapping().allIndexedEntityNames();
}
@Override
public Set<Class<?>> allIndexedEntityJavaClasses() {
// Create the mapping is a very expensive and blocking operation.
// It is better to avoid to invoke it if we don't need it.
long stamp = stampedLock.tryReadLock();
if (stamp == 0L) {
return Collections.singleton(byte[].class);
}
try {
if (!searchMappingRef.available()) {
return Collections.singleton(byte[].class);
}
return mapping().allIndexedEntityJavaClasses();
} finally {
stampedLock.unlockRead(stamp);
}
}
@Override
public Class<?> toConvertedEntityJavaClass(Object value) {
return mapping().toConvertedEntityJavaClass(value);
}
@Override
public Map<String, IndexMetamodel> metamodel() {
return mapping().metamodel();
}
@Override
public int genericIndexingFailures() {
long stamp = stampedLock.tryReadLock();
if (stamp == 0L) {
return -1;
}
try {
if (!searchMappingRef.available()) {
return -1;
}
return mapping().genericIndexingFailures();
} finally {
stampedLock.unlockRead(stamp);
}
}
@Override
public int entityIndexingFailures() {
long stamp = stampedLock.tryReadLock();
if (stamp == 0L) {
return -1;
}
try {
if (!searchMappingRef.available()) {
return -1;
}
return mapping().entityIndexingFailures();
} finally {
stampedLock.unlockRead(stamp);
}
}
@Override
public void reload() {
long stamp = stampedLock.writeLock();
queryCache.clear(cache.getName());
try {
searchMappingRef.get().close();
searchMappingRef = new LazyRef<>(this::createMapping);
} finally {
stampedLock.unlockWrite(stamp);
}
}
@Override
public void restart() {
long stamp = stampedLock.writeLock();
try {
restarting = true;
InfinispanMapping mapping = (InfinispanMapping) searchMappingRef.get();
searchMappingRef = new LazyRef<>(() -> createMapping(Optional.of(mapping.getIntegration())));
searchMappingRef.get(); // create it now
} finally {
restarting = false;
stampedLock.unlockWrite(stamp);
}
}
private SearchMapping mapping() {
long stamp = stampedLock.tryOptimisticRead();
SearchMapping searchMapping = searchMappingRef.get();
if (!stampedLock.validate(stamp)) {
stamp = stampedLock.readLock();
try {
searchMapping = searchMappingRef.get();
} finally {
stampedLock.unlockRead(stamp);
}
}
return searchMapping;
}
private SearchMapping createMapping() {
return createMapping(Optional.empty());
}
private SearchMapping createMapping(Optional<SearchIntegration> previousIntegration) {
IndexingConfiguration indexingConfiguration = cache.getCacheConfiguration().indexing();
Set<String> indexedEntityTypes = indexingConfiguration.indexedEntityTypes();
DataConversion valueDataConversion = cache.getAdvancedCache().getValueDataConversion();
SearchMapping searchMapping = null;
if (commonBuilding != null) {
SearchMappingBuilder builder = SerializationContextSearchMapping.createBuilder(commonBuilding, entityLoader, indexedEntityTypes, serCtx);
searchMapping = builder != null ? builder.build(previousIntegration) : null;
}
if (indexingConfiguration.enabled()) {
if (valueDataConversion.getStorageMediaType().match(APPLICATION_PROTOSTREAM)) {
// Try to resolve the indexed type names to protobuf type names.
Set<String> knownTypes = protobufMetadataManager.getKnownTypes();
for (String typeName : indexedEntityTypes) {
if (!knownTypes.contains(typeName)) {
if (searchMapping != null) searchMapping.close();
throw log.unknownType(typeName);
}
if (searchMapping == null || searchMapping.indexedEntity(typeName) == null) {
if (searchMapping != null) searchMapping.close();
throw log.typeNotIndexed(typeName);
}
}
}
}
return searchMapping;
}
}
| 8,922
| 31.097122
| 146
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/ProtobufObjectReflectionMatcher.java
|
package org.infinispan.query.remote.impl;
import java.io.IOException;
import org.infinispan.commons.CacheException;
import org.infinispan.objectfilter.impl.ReflectionMatcher;
import org.infinispan.objectfilter.impl.syntax.parser.EntityNameResolver;
import org.infinispan.protostream.ProtobufUtil;
import org.infinispan.protostream.SerializationContext;
/**
* A sub-class of ReflectionMatcher that is able to lookup classes by their protobuf type name and can work with object
* storage.
*
* @author anistor@redhat.com
* @since 7.0
*/
final class ProtobufObjectReflectionMatcher extends ReflectionMatcher {
private final SerializationContext serializationContext;
private ProtobufObjectReflectionMatcher(EntityNameResolver entityNameResolver, SerializationContext serializationContext) {
super(entityNameResolver);
this.serializationContext = serializationContext;
}
static ProtobufObjectReflectionMatcher create(EntityNameResolver<Class<?>> entityNameResolver, SerializationContext ctx) {
return new ProtobufObjectReflectionMatcher(entityNameResolver, ctx);
}
/**
* Marshals the instance using Protobuf.
*
* @param instance never null
* @return the converted/decorated instance
*/
@Override
protected Object convert(Object instance) {
try {
return ProtobufUtil.toWrappedByteArray(serializationContext, instance);
} catch (IOException e) {
throw new CacheException(e);
}
}
}
| 1,488
| 31.369565
| 126
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/ProtobufEntityNameResolver.java
|
package org.infinispan.query.remote.impl;
import org.infinispan.objectfilter.impl.syntax.parser.EntityNameResolver;
import org.infinispan.protostream.SerializationContext;
/**
* @author anistor@redhat.com
* @since 9.1
*/
final class ProtobufEntityNameResolver implements EntityNameResolver<Class<?>> {
private final SerializationContext serializationContext;
ProtobufEntityNameResolver(SerializationContext serializationContext) {
this.serializationContext = serializationContext;
}
@Override
public Class<?> resolve(String entityName) {
return serializationContext.canMarshall(entityName) ? serializationContext.getMarshaller(entityName).getJavaClass() : null;
}
}
| 704
| 29.652174
| 129
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/ProtobufRemoteQueryManager.java
|
package org.infinispan.query.remote.impl;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_PROTOSTREAM;
import org.infinispan.AdvancedCache;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.dataconversion.Transcoder;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.encoding.impl.StorageConfigurationManager;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.marshall.core.EncoderRegistry;
import org.infinispan.objectfilter.Matcher;
import org.infinispan.objectfilter.impl.ProtobufMatcher;
import org.infinispan.protostream.SerializationContext;
/**
* {@link RemoteQueryManager} suitable for caches storing protobuf.
*
* @since 9.2
*/
final class ProtobufRemoteQueryManager extends BaseRemoteQueryManager {
private final RemoteQueryEngine queryEngine;
private final Transcoder protobufTranscoder;
ProtobufRemoteQueryManager(AdvancedCache<?, ?> cache, ComponentRegistry cr, SerializationContext serCtx, QuerySerializers querySerializers) {
super(cache, querySerializers, cr);
Matcher matcher = new ObjectProtobufMatcher(serCtx, ProtobufFieldIndexingMetadata::new, cache);
cr.registerComponent(matcher, ProtobufMatcher.class);
Configuration configuration = cache.getCacheConfiguration();
boolean isIndexed = configuration.indexing().enabled();
boolean customStorage = configuration.encoding().valueDataType().isMediaTypeChanged();
MediaType valueMediaType = getValueDataConversion().getStorageMediaType();
boolean isProtoBuf = valueMediaType.match(APPLICATION_PROTOSTREAM);
if (isProtoBuf || !customStorage && isIndexed) {
StorageConfigurationManager storageConfigurationManager = cr.getComponent(StorageConfigurationManager.class);
storageConfigurationManager.overrideWrapper(storageConfigurationManager.getKeyWrapper(), ProtobufWrapper.INSTANCE);
}
this.queryEngine = new RemoteQueryEngine(cache, isIndexed);
EncoderRegistry encoderRegistry = cr.getGlobalComponentRegistry().getComponent(EncoderRegistry.class);
this.protobufTranscoder = encoderRegistry.getTranscoder(APPLICATION_PROTOSTREAM, APPLICATION_OBJECT);
}
@Override
public Class<? extends Matcher> getMatcherClass(MediaType mediaType) {
return ProtobufMatcher.class;
}
@Override
public RemoteQueryEngine getQueryEngine(AdvancedCache<?, ?> cache) {
return queryEngine;
}
@Override
public Object encodeFilterResult(Object filterResult) {
return protobufTranscoder.transcode(filterResult, APPLICATION_OBJECT, APPLICATION_PROTOSTREAM);
}
}
| 2,760
| 44.262295
| 144
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/QuerySerializer.java
|
package org.infinispan.query.remote.impl;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.query.remote.client.impl.QueryRequest;
/**
* Handles serialization of query results.
*
* @since 9.4
*/
interface QuerySerializer<QR> {
QueryRequest decodeQueryRequest(byte[] queryRequest, MediaType mediaType);
QR createQueryResponse(RemoteQueryResult remoteQueryResult);
byte[] encodeQueryResponse(Object queryResponse, MediaType requestType);
}
| 485
| 23.3
| 77
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/ObjectRemoteQueryEngine.java
|
package org.infinispan.query.remote.impl;
import java.util.Map;
import org.infinispan.AdvancedCache;
import org.infinispan.objectfilter.Matcher;
import org.infinispan.protostream.descriptors.Descriptor;
import org.infinispan.query.core.impl.EmbeddedQueryFactory;
import org.infinispan.query.dsl.Query;
import org.infinispan.query.dsl.embedded.impl.QueryEngine;
/**
* A QueryEngine for remote, dealing with entries stored as objects rather than marshalled.
*
* @author anistor@redhat.com
* @since 9.0
*/
class ObjectRemoteQueryEngine extends QueryEngine<Descriptor> {
private final EmbeddedQueryFactory queryFactory = new EmbeddedQueryFactory(this);
ObjectRemoteQueryEngine(AdvancedCache<?, ?> cache, boolean isIndexed, Class<? extends Matcher> matcherImplClass) {
super(cache.getAdvancedCache(), isIndexed, matcherImplClass);
}
Query<Object> makeQuery(String queryString, Map<String, Object> namedParameters, long startOffset, int maxResults,
int hitCountAccuracy, boolean local) {
Query<Object> query = queryFactory.create(queryString);
query.startOffset(startOffset);
query.maxResults(maxResults);
query.hitCountAccuracy(hitCountAccuracy);
query.local(local);
if (namedParameters != null) {
query.setParameters(namedParameters);
}
return query;
}
}
| 1,367
| 34.076923
| 117
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/ProtobufMetadataManagerImpl.java
|
package org.infinispan.query.remote.impl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.management.MBeanException;
import org.infinispan.Cache;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.commons.marshall.UserContextInitializerImpl;
import org.infinispan.commons.util.ServiceFinder;
import org.infinispan.configuration.cache.AuthorizationConfigurationBuilder;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalAuthorizationConfiguration;
import org.infinispan.configuration.global.GlobalConfiguration;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.annotations.Start;
import org.infinispan.factories.impl.BasicComponentRegistry;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.interceptors.AsyncInterceptorChain;
import org.infinispan.interceptors.impl.EntryWrappingInterceptor;
import org.infinispan.jmx.annotations.MBean;
import org.infinispan.jmx.annotations.ManagedAttribute;
import org.infinispan.jmx.annotations.ManagedOperation;
import org.infinispan.jmx.annotations.Parameter;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.marshall.protostream.impl.SerializationContextRegistry;
import org.infinispan.protostream.BaseMarshaller;
import org.infinispan.protostream.DescriptorParserException;
import org.infinispan.protostream.ProtobufUtil;
import org.infinispan.protostream.SerializationContext;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.protostream.config.Configuration;
import org.infinispan.protostream.types.java.CommonContainerTypesSchema;
import org.infinispan.protostream.types.java.CommonTypesSchema;
import org.infinispan.query.remote.ProtobufMetadataManager;
import org.infinispan.query.remote.client.ProtobufMetadataManagerConstants;
import org.infinispan.query.remote.client.impl.MarshallerRegistration;
import org.infinispan.query.remote.impl.indexing.infinispan.InfinispanAnnotations;
import org.infinispan.query.remote.impl.indexing.search5.Search5Annotations;
import org.infinispan.query.remote.impl.logging.Log;
import org.infinispan.registry.InternalCacheRegistry;
import org.infinispan.security.actions.SecurityActions;
import org.infinispan.security.impl.CreatePermissionConfigurationBuilder;
import org.infinispan.transaction.LockingMode;
import org.infinispan.transaction.TransactionMode;
import org.infinispan.util.concurrent.IsolationLevel;
/**
* @author anistor@redhat.com
* @since 7.0
*/
@MBean(objectName = ProtobufMetadataManagerConstants.OBJECT_NAME,
description = "Component that acts as a manager and persistent container for Protocol Buffers schema definitions in the scope of a CacheManger.")
@Scope(Scopes.GLOBAL)
public final class ProtobufMetadataManagerImpl implements ProtobufMetadataManager {
private static final Log log = LogFactory.getLog(ProtobufMetadataManagerImpl.class, Log.class);
private final SerializationContext serCtx;
private volatile Cache<String, String> protobufSchemaCache;
@Inject
EmbeddedCacheManager cacheManager;
@Inject
InternalCacheRegistry internalCacheRegistry;
@Inject
SerializationContextRegistry serializationContextRegistry;
public ProtobufMetadataManagerImpl() {
Configuration.Builder protostreamCfgBuilder = Configuration.builder();
Search5Annotations.configure(protostreamCfgBuilder);
InfinispanAnnotations.configure(protostreamCfgBuilder);
serCtx = ProtobufUtil.newSerializationContext(protostreamCfgBuilder.build());
try {
MarshallerRegistration.init(serCtx);
} catch (DescriptorParserException e) {
throw new CacheException("Failed to initialise the Protobuf serialization context", e);
}
register(new CommonTypesSchema());
register(new CommonContainerTypesSchema());
register(new UserContextInitializerImpl());
}
void register(SerializationContextInitializer initializer) {
initializer.registerSchema(getSerializationContext());
initializer.registerMarshallers(getSerializationContext());
}
@Start
void start() {
GlobalConfiguration globalConfiguration = cacheManager.getCacheManagerConfiguration();
internalCacheRegistry.registerInternalCache(PROTOBUF_METADATA_CACHE_NAME,
getProtobufMetadataCacheConfig(globalConfiguration).build(),
EnumSet.of(InternalCacheRegistry.Flag.USER, InternalCacheRegistry.Flag.PROTECTED, InternalCacheRegistry.Flag.PERSISTENT));
Collection<SerializationContextInitializer> initializers = globalConfiguration.serialization().contextInitializers();
if (initializers == null || initializers.isEmpty()) {
initializers = ServiceFinder.load(SerializationContextInitializer.class, globalConfiguration.classLoader());
}
processSerializationContextInitializer(initializers);
}
private void processSerializationContextInitializer(Iterable<SerializationContextInitializer> initializers) {
if (initializers != null) {
for (SerializationContextInitializer sci : initializers) {
log.debugf("Registering protostream serialization context initializer: %s", sci.getClass().getName());
try {
sci.registerSchema(serCtx);
sci.registerMarshallers(serCtx);
} catch (Exception e) {
throw log.errorInitializingSerCtx(e);
}
}
}
}
/**
* Adds an interceptor to the protobuf manager cache to detect entry updates and sync the SerializationContext.
*
* @param cacheComponentRegistry the component registry of the protobuf manager cache
*/
void addProtobufMetadataManagerInterceptor(BasicComponentRegistry cacheComponentRegistry) {
ProtobufMetadataManagerInterceptor interceptor = new ProtobufMetadataManagerInterceptor();
cacheComponentRegistry.registerComponent(ProtobufMetadataManagerInterceptor.class, interceptor, true);
cacheComponentRegistry.addDynamicDependency(AsyncInterceptorChain.class.getName(), ProtobufMetadataManagerInterceptor.class.getName());
cacheComponentRegistry.getComponent(AsyncInterceptorChain.class).wired().addInterceptorAfter(interceptor, EntryWrappingInterceptor.class);
}
/**
* Adds a stop dependency on ___protobuf_metadata cache. This must be invoked for each cache that uses protobuf.
*
* @param dependantCacheName the name of the cache depending on the protobuf metadata cache
*/
void addCacheDependency(String dependantCacheName) {
SecurityActions.addCacheDependency(cacheManager, dependantCacheName, PROTOBUF_METADATA_CACHE_NAME);
}
/**
* Get the protobuf schema cache (lazily).
*/
public Cache<String, String> getCache() {
if (protobufSchemaCache == null) {
protobufSchemaCache = SecurityActions.getUnwrappedCache(cacheManager, PROTOBUF_METADATA_CACHE_NAME);
}
return protobufSchemaCache;
}
private static ConfigurationBuilder getProtobufMetadataCacheConfig(GlobalConfiguration globalConfiguration) {
CacheMode cacheMode = globalConfiguration.isClustered() ? CacheMode.REPL_SYNC : CacheMode.LOCAL;
ConfigurationBuilder cfg = new ConfigurationBuilder();
cfg.transaction()
.transactionMode(TransactionMode.TRANSACTIONAL).invocationBatching().enable()
.transaction().lockingMode(LockingMode.PESSIMISTIC)
.locking().isolationLevel(IsolationLevel.READ_COMMITTED).useLockStriping(false)
.clustering().cacheMode(cacheMode)
.stateTransfer().fetchInMemoryState(true).awaitInitialTransfer(false)
.encoding().key().mediaType(MediaType.APPLICATION_OBJECT_TYPE)
.encoding().value().mediaType(MediaType.APPLICATION_OBJECT_TYPE);
GlobalAuthorizationConfiguration globalAuthz = globalConfiguration.security().authorization();
if (globalAuthz.enabled()) {
if (!globalAuthz.hasRole(SCHEMA_MANAGER_ROLE)) {
globalAuthz.addRole(GlobalAuthorizationConfiguration.DEFAULT_ROLES.get(SCHEMA_MANAGER_ROLE));
}
AuthorizationConfigurationBuilder authorization = cfg.security().authorization().enable();
// Copy all global roles
globalAuthz.roles().keySet().forEach(role -> authorization.role(role));
// Add a special module which translates permissions
cfg.addModule(CreatePermissionConfigurationBuilder.class);
}
return cfg;
}
@Override
public void registerMarshaller(BaseMarshaller<?> marshaller) {
serCtx.registerMarshaller(marshaller);
serializationContextRegistry.addMarshaller(SerializationContextRegistry.MarshallerType.GLOBAL, marshaller);
}
@Override
public void unregisterMarshaller(BaseMarshaller<?> marshaller) {
serCtx.unregisterMarshaller(marshaller);
}
@ManagedOperation(description = "Registers a Protobuf definition file", displayName = "Register a Protofile")
@Override
public void registerProtofile(@Parameter(name = "fileName", description = "the name of the .proto file") String fileName,
@Parameter(name = "contents", description = "contents of the file") String contents) {
getCache().put(fileName, contents);
}
@ManagedOperation(description = "Registers multiple Protobuf definition files", displayName = "Register Protofiles")
@Override
public void registerProtofiles(@Parameter(name = "fileNames", description = "names of the protofiles") String[] fileNames,
@Parameter(name = "fileContents", description = "content of the files") String[] contents) throws Exception {
if (fileNames.length != contents.length) {
throw new MBeanException(new IllegalArgumentException("invalid parameter sizes"));
}
Map<String, String> files = new HashMap<>(fileNames.length);
for (int i = 0; i < fileNames.length; i++) {
files.put(fileNames[i], contents[i]);
}
getCache().putAll(files);
}
@ManagedOperation(description = "Unregisters a Protobuf definition files", displayName = "Unregister a Protofiles")
@Override
public void unregisterProtofile(@Parameter(name = "fileName", description = "the name of the .proto file") String fileName) {
if (getCache().remove(fileName) == null) {
throw new IllegalArgumentException("File does not exist : " + fileName);
}
}
@ManagedOperation(description = "Unregisters multiple Protobuf definition files", displayName = "Unregister Protofiles")
@Override
public void unregisterProtofiles(@Parameter(name = "fileNames", description = "names of the protofiles") String[] fileNames) {
for (String fileName : fileNames) {
if (getCache().remove(fileName) == null) {
throw new IllegalArgumentException("File does not exist : " + fileName);
}
}
}
@ManagedAttribute(description = "The names of all Protobuf files", displayName = "Protofile Names")
@Override
public String[] getProtofileNames() {
List<String> fileNames = new ArrayList<>();
for (String k : getCache().keySet()) {
if (k.endsWith(PROTO_KEY_SUFFIX)) {
fileNames.add(k);
}
}
Collections.sort(fileNames);
return fileNames.toArray(new String[fileNames.size()]);
}
@ManagedOperation(description = "Get the contents of a protobuf definition file", displayName = "Get Protofile")
@Override
public String getProtofile(@Parameter(name = "fileName", description = "the name of the .proto file") String fileName) {
if (!fileName.endsWith(PROTO_KEY_SUFFIX)) {
throw new IllegalArgumentException("The file name must have \".proto\" suffix");
}
String fileContents = getCache().get(fileName);
if (fileContents == null) {
throw new IllegalArgumentException("File does not exist : " + fileName);
}
return fileContents;
}
@ManagedAttribute(description = "The names of the files that have errors, if any", displayName = "Files With Errors")
@Override
public String[] getFilesWithErrors() {
String filesWithErrors = getCache().get(ERRORS_KEY_SUFFIX);
if (filesWithErrors == null) {
return null;
}
String[] fileNames = filesWithErrors.split("\n");
Arrays.sort(fileNames);
return fileNames;
}
@ManagedOperation(description = "Obtains the errors associated with a protobuf definition file", displayName = "Get Errors For A File")
@Override
public String getFileErrors(@Parameter(name = "fileName", description = "the name of the .proto file") String fileName) {
if (!fileName.endsWith(PROTO_KEY_SUFFIX)) {
throw new IllegalArgumentException("The file name must have \".proto\" suffix");
}
if (!getCache().containsKey(fileName)) {
throw new IllegalArgumentException("File does not exist : " + fileName);
}
return getCache().get(fileName + ERRORS_KEY_SUFFIX);
}
public Set<String> getKnownTypes() {
return getSerializationContext().getGenericDescriptors().keySet();
}
SerializationContext getSerializationContext() {
return serCtx;
}
/**
* Obtains the ProtobufMetadataManagerImpl instance associated to a cache manager.
*
* @param cacheManager a cache manager instance
* @return the ProtobufMetadataManagerImpl instance associated to a cache manager.
*/
private static ProtobufMetadataManagerImpl getProtobufMetadataManager(EmbeddedCacheManager cacheManager) {
if (cacheManager == null) {
throw new IllegalArgumentException("cacheManager cannot be null");
}
ProtobufMetadataManagerImpl metadataManager = (ProtobufMetadataManagerImpl) cacheManager.getGlobalComponentRegistry().getComponent(ProtobufMetadataManager.class);
if (metadataManager == null) {
throw new IllegalStateException("ProtobufMetadataManager not initialised yet!");
}
return metadataManager;
}
/**
* Obtains the protobuf serialization context of the ProtobufMetadataManager instance associated to a cache manager.
*
* @param cacheManager a cache manager instance
* @return the protobuf {@link SerializationContext}
*/
public static SerializationContext getSerializationContext(EmbeddedCacheManager cacheManager) {
return getProtobufMetadataManager(cacheManager).getSerializationContext();
}
}
| 14,933
| 44.950769
| 168
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/QueryFacadeImpl.java
|
package org.infinispan.query.remote.impl;
import org.infinispan.AdvancedCache;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.query.remote.client.impl.QueryRequest;
import org.infinispan.query.remote.impl.logging.Log;
import org.infinispan.security.AuthorizationManager;
import org.infinispan.security.AuthorizationPermission;
import org.infinispan.server.core.QueryFacade;
import org.kohsuke.MetaInfServices;
/**
* A query facade implementation for both Lucene based queries and non-indexed in-memory queries. All work is delegated
* to {@link RemoteQueryEngine}.
*
* @author anistor@redhat.com
* @since 6.0
*/
@MetaInfServices
public final class QueryFacadeImpl implements QueryFacade {
private static final Log log = LogFactory.getLog(QueryFacadeImpl.class, Log.class);
@Override
public byte[] query(AdvancedCache<?, ?> cache, byte[] query) {
AuthorizationManager authorizationManager = SecurityActions.getCacheAuthorizationManager(cache);
if (authorizationManager != null) {
authorizationManager.checkPermission(AuthorizationPermission.BULK_READ);
}
RemoteQueryManager remoteQueryManager = SecurityActions.getRemoteQueryManager(cache);
if (remoteQueryManager.getQueryEngine(cache) == null) { //todo [anistor] remoteQueryManager should be null if not queryable
throw log.queryingNotEnabled(cache.getName());
}
try {
MediaType requestMediaType = cache.getValueDataConversion().getRequestMediaType();
QueryRequest request = remoteQueryManager.decodeQueryRequest(query, requestMediaType);
int startOffset = request.getStartOffset().intValue();
int maxResults = request.getMaxResults();
int hitCountAccuracy = request.hitCountAccuracy();
boolean local = request.isLocal();
return remoteQueryManager.executeQuery(request.getQueryString(),
request.getNamedParametersMap(), startOffset, maxResults, hitCountAccuracy, cache, requestMediaType, local);
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debugf(e, "Error executing remote query : %s", e.getMessage());
}
throw e;
}
}
}
| 2,279
| 40.454545
| 130
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/RemoteQueryServerBlockHoundIntegration.java
|
package org.infinispan.query.remote.impl;
import org.kohsuke.MetaInfServices;
import reactor.blockhound.BlockHound;
import reactor.blockhound.integration.BlockHoundIntegration;
@MetaInfServices
public class RemoteQueryServerBlockHoundIntegration implements BlockHoundIntegration {
@Override
public void applyTo(BlockHound.Builder builder) {
// the registration of a new ProtoSchema is invoked infrequently enough
builder.allowBlockingCallsInside(ProtobufMetadataManagerInterceptor.class.getName(), "registerFileDescriptorSource");
}
}
| 560
| 32
| 123
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/RemoteQueryResult.java
|
package org.infinispan.query.remote.impl;
import java.util.List;
public final class RemoteQueryResult {
private final String[] projections;
private final int hitCount;
private final boolean hitCountExact;
private final List<Object> results;
RemoteQueryResult(String[] projections, int hitCount, boolean hitCountExact, List<Object> results) {
this.projections = projections;
this.hitCount = hitCount;
this.hitCountExact = hitCountExact;
this.results = results;
}
public String[] getProjections() {
return projections;
}
public int hitCount() {
return hitCount;
}
public boolean hitCountExact() {
return hitCountExact;
}
public List<Object> getResults() {
return results;
}
}
| 771
| 21.705882
| 103
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/ProtobufFieldIndexingMetadata.java
|
package org.infinispan.query.remote.impl;
import static org.infinispan.query.remote.impl.indexing.IndexingMetadata.findProcessedAnnotation;
import java.util.function.BiFunction;
import org.infinispan.objectfilter.impl.syntax.IndexedFieldProvider;
import org.infinispan.protostream.descriptors.Descriptor;
import org.infinispan.protostream.descriptors.FieldDescriptor;
import org.infinispan.protostream.descriptors.JavaType;
import org.infinispan.query.remote.impl.indexing.FieldMapping;
import org.infinispan.query.remote.impl.indexing.IndexingMetadata;
import org.infinispan.query.remote.impl.mapping.reference.MessageReferenceProvider;
/**
* Tests if a field is indexed by examining the Protobuf metadata.
*
* @author anistor@redhat.com
* @since 8.0
*/
final class ProtobufFieldIndexingMetadata implements IndexedFieldProvider.FieldIndexingMetadata {
private final Descriptor messageDescriptor;
ProtobufFieldIndexingMetadata(Descriptor messageDescriptor) {
if (messageDescriptor == null) {
throw new IllegalArgumentException("argument cannot be null");
}
this.messageDescriptor = messageDescriptor;
}
@Override
public boolean isIndexed(String[] propertyPath) {
return getFlag(propertyPath, IndexingMetadata::isFieldSearchable);
}
@Override
public boolean isAnalyzed(String[] propertyPath) {
return getFlag(propertyPath, IndexingMetadata::isFieldAnalyzed);
}
@Override
public boolean isProjectable(String[] propertyPath) {
return getFlag(propertyPath, IndexingMetadata::isFieldProjectable);
}
@Override
public boolean isSortable(String[] propertyPath) {
return getFlag(propertyPath, IndexingMetadata::isFieldSortable);
}
@Override
public Object getNullMarker(String[] propertyPath) {
Descriptor md = messageDescriptor;
int i = 0;
for (String p : propertyPath) {
i++;
FieldDescriptor field = md.findFieldByName(p);
if (field == null) {
break;
}
if (i == propertyPath.length) {
IndexingMetadata indexingMetadata = findProcessedAnnotation(md, IndexingMetadata.INDEXED_ANNOTATION);
return indexingMetadata == null ? null : indexingMetadata.getNullMarker(field.getName());
}
if (field.getJavaType() != JavaType.MESSAGE) {
break;
}
md = field.getMessageType();
}
return null;
}
private boolean getFlag(String[] propertyPath, BiFunction<IndexingMetadata, String, Boolean> metadataFun) {
Descriptor md = messageDescriptor;
for (String p : propertyPath) {
FieldDescriptor field = md.findFieldByName(p);
if (field == null) {
return false;
}
IndexingMetadata indexingMetadata = findProcessedAnnotation(md, IndexingMetadata.INDEXED_ANNOTATION);
if (indexingMetadata == null || !indexingMetadata.isIndexed()){
return false;
}
if (field.getJavaType() == JavaType.MESSAGE &&
!MessageReferenceProvider.COMMON_MESSAGE_TYPES.contains(field.getTypeName())) {
FieldMapping embeddedMapping = indexingMetadata.getFieldMapping(p);
if (embeddedMapping == null || !embeddedMapping.searchable()) {
return false;
}
md = field.getMessageType();
continue;
}
return metadataFun.apply(indexingMetadata, field.getName());
}
return false;
}
}
| 3,521
| 33.194175
| 113
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/JsonQuerySerializer.java
|
package org.infinispan.query.remote.impl;
import static java.util.stream.Collectors.toList;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JSON;
import java.util.List;
import java.util.stream.Collectors;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.dataconversion.Transcoder;
import org.infinispan.commons.dataconversion.internal.Json;
import org.infinispan.query.remote.client.impl.QueryRequest;
import org.infinispan.query.remote.json.Hit;
import org.infinispan.query.remote.json.JsonQueryResponse;
import org.infinispan.query.remote.json.JsonQueryResult;
import org.infinispan.query.remote.json.ProjectedJsonResult;
/**
* Handles serialization of Query response in JSON format.
*
* @since 9.4
*/
class JsonQuerySerializer implements QuerySerializer<JsonQueryResponse> {
private final MediaType storageMediaTye;
private final Transcoder transcoderFromStorage;
JsonQuerySerializer(MediaType storageMediaTye, Transcoder transcoderFromStorage) {
this.storageMediaTye = storageMediaTye;
this.transcoderFromStorage = transcoderFromStorage;
}
@Override
public QueryRequest decodeQueryRequest(byte[] queryRequest, MediaType mediaType) {
return QueryRequest.fromJson(Json.read(new String(queryRequest, mediaType.getCharset())));
}
@Override
public JsonQueryResponse createQueryResponse(RemoteQueryResult remoteQueryResult) {
int hitCount = remoteQueryResult.hitCount();
boolean hitCountExact = remoteQueryResult.hitCountExact();
String[] projections = remoteQueryResult.getProjections();
JsonQueryResponse response;
if (projections == null) {
List<Object> results = remoteQueryResult.getResults().stream()
.map(o -> transcoderFromStorage.transcode(o, storageMediaTye, APPLICATION_JSON))
.collect(toList());
List<Hit> hits = results.stream().map(Hit::new).collect(Collectors.toList());
response = new JsonQueryResult(hits, hitCount, hitCountExact);
} else {
response = new ProjectedJsonResult(hitCount, hitCountExact, projections, remoteQueryResult.getResults());
}
return response;
}
@Override
public byte[] encodeQueryResponse(Object queryResponse, MediaType destinationType) {
return ((JsonQueryResponse) queryResponse).toJson().toString().getBytes(destinationType.getCharset());
}
}
| 2,439
| 38.354839
| 114
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/LifecycleManager.java
|
package org.infinispan.query.remote.impl;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JSON;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT;
import static org.infinispan.query.remote.client.ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME;
import java.util.Map;
import javax.management.ObjectName;
import org.infinispan.AdvancedCache;
import org.infinispan.Cache;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.dataconversion.ByteArrayWrapper;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.dataconversion.Transcoder;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.ContentTypeConfiguration;
import org.infinispan.configuration.global.GlobalConfiguration;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.factories.GlobalComponentRegistry;
import org.infinispan.factories.annotations.InfinispanModule;
import org.infinispan.factories.impl.BasicComponentRegistry;
import org.infinispan.jmx.CacheManagerJmxRegistration;
import org.infinispan.lifecycle.ModuleLifecycle;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.marshall.core.EncoderRegistry;
import org.infinispan.marshall.protostream.impl.SerializationContextRegistry;
import org.infinispan.protostream.SerializationContext;
import org.infinispan.query.core.impl.QueryCache;
import org.infinispan.query.core.stats.IndexStatistics;
import org.infinispan.query.core.stats.impl.LocalQueryStatistics;
import org.infinispan.query.impl.EntityLoader;
import org.infinispan.query.remote.ProtobufMetadataManager;
import org.infinispan.query.remote.client.impl.Externalizers.QueryRequestExternalizer;
import org.infinispan.query.remote.client.impl.MarshallerRegistration;
import org.infinispan.query.remote.client.impl.QueryRequest;
import org.infinispan.query.remote.impl.filter.ContinuousQueryResultExternalizer;
import org.infinispan.query.remote.impl.filter.FilterResultExternalizer;
import org.infinispan.query.remote.impl.filter.IckleBinaryProtobufFilterAndConverter;
import org.infinispan.query.remote.impl.filter.IckleContinuousQueryProtobufCacheEventFilterConverter;
import org.infinispan.query.remote.impl.filter.IckleProtobufCacheEventFilterConverter;
import org.infinispan.query.remote.impl.filter.IckleProtobufFilterAndConverter;
import org.infinispan.query.remote.impl.persistence.PersistenceContextInitializerImpl;
import org.infinispan.query.stats.impl.LocalIndexStatistics;
import org.infinispan.registry.InternalCacheRegistry;
import org.infinispan.search.mapper.mapping.SearchMapping;
import org.infinispan.search.mapper.mapping.SearchMappingCommonBuilding;
/**
* Initializes components for remote query. Each cache manager has its own instance of this class during its lifetime.
*
* @author anistor@redhat.com
* @since 6.0
*/
@InfinispanModule(name = "remote-query-server", requiredModules = {"core", "query", "server-core"})
public final class LifecycleManager implements ModuleLifecycle {
@Override
public void cacheManagerStarting(GlobalComponentRegistry gcr, GlobalConfiguration globalCfg) {
org.infinispan.query.impl.LifecycleManager queryModule = gcr.getModuleLifecycle(org.infinispan.query.impl.LifecycleManager.class);
if (queryModule != null) {
queryModule.enableRemoteQuery();
}
Map<Integer, AdvancedExternalizer<?>> externalizerMap = globalCfg.serialization().advancedExternalizers();
externalizerMap.put(ExternalizerIds.ICKLE_PROTOBUF_CACHE_EVENT_FILTER_CONVERTER, new IckleProtobufCacheEventFilterConverter.Externalizer());
externalizerMap.put(ExternalizerIds.ICKLE_PROTOBUF_FILTER_AND_CONVERTER, new IckleProtobufFilterAndConverter.Externalizer());
externalizerMap.put(ExternalizerIds.ICKLE_CONTINUOUS_QUERY_CACHE_EVENT_FILTER_CONVERTER, new IckleContinuousQueryProtobufCacheEventFilterConverter.Externalizer());
externalizerMap.put(ExternalizerIds.ICKLE_BINARY_PROTOBUF_FILTER_AND_CONVERTER, new IckleBinaryProtobufFilterAndConverter.Externalizer());
externalizerMap.put(ExternalizerIds.ICKLE_CONTINUOUS_QUERY_RESULT, new ContinuousQueryResultExternalizer());
externalizerMap.put(ExternalizerIds.ICKLE_FILTER_RESULT, new FilterResultExternalizer());
BasicComponentRegistry bcr = gcr.getComponent(BasicComponentRegistry.class);
SerializationContextRegistry ctxRegistry = gcr.getComponent(SerializationContextRegistry.class);
ctxRegistry.addContextInitializer(SerializationContextRegistry.MarshallerType.PERSISTENCE, new PersistenceContextInitializerImpl());
ctxRegistry.addContextInitializer(SerializationContextRegistry.MarshallerType.GLOBAL, MarshallerRegistration.INSTANCE);
initProtobufMetadataManager(bcr);
EmbeddedCacheManager cacheManager = gcr.getComponent(EmbeddedCacheManager.class);
cacheManager.getClassAllowList()
.addClasses(QueryRequest.class, QueryRequestExternalizer.class);
}
private void initProtobufMetadataManager(BasicComponentRegistry bcr) {
ProtobufMetadataManagerImpl protobufMetadataManager = new ProtobufMetadataManagerImpl();
bcr.registerComponent(ProtobufMetadataManager.class, protobufMetadataManager, true).running();
EncoderRegistry encoderRegistry = bcr.getComponent(EncoderRegistry.class).wired();
encoderRegistry.registerWrapper(ProtobufWrapper.INSTANCE);
}
@Override
public void cacheManagerStarted(GlobalComponentRegistry gcr) {
BasicComponentRegistry bcr = gcr.getComponent(BasicComponentRegistry.class);
ProtobufMetadataManagerImpl protobufMetadataManager =
(ProtobufMetadataManagerImpl) bcr.getComponent(ProtobufMetadataManager.class).running();
// if not already running, start it
protobufMetadataManager.getCache();
GlobalConfiguration globalCfg = gcr.getGlobalConfiguration();
if (globalCfg.jmx().enabled()) {
registerProtobufMetadataManagerMBean(protobufMetadataManager, globalCfg, bcr);
}
}
private void registerProtobufMetadataManagerMBean(ProtobufMetadataManagerImpl protobufMetadataManager,
GlobalConfiguration globalConfig, BasicComponentRegistry bcr) {
CacheManagerJmxRegistration jmxRegistration = bcr.getComponent(CacheManagerJmxRegistration.class).running();
try {
jmxRegistration.registerMBean(protobufMetadataManager, getRemoteQueryGroupName(globalConfig));
} catch (Exception e) {
throw new CacheException("Unable to register ProtobufMetadataManager MBean", e);
}
}
private String getRemoteQueryGroupName(GlobalConfiguration globalConfig) {
return "type=RemoteQuery,name=" + ObjectName.quote(globalConfig.cacheManagerName());
}
/**
* Registers the interceptor in the ___protobuf_metadata cache before it gets started. Also creates query components
* for user caches.
*/
@Override
public void cacheStarting(ComponentRegistry cr, Configuration cfg, String cacheName) {
BasicComponentRegistry gcr = cr.getGlobalComponentRegistry().getComponent(BasicComponentRegistry.class);
LocalQueryStatistics queryStatistics = cr.getComponent(LocalQueryStatistics.class);
if (PROTOBUF_METADATA_CACHE_NAME.equals(cacheName)) {
// a protobuf metadata cache is starting, need to register the interceptor
ProtobufMetadataManagerImpl protobufMetadataManager =
(ProtobufMetadataManagerImpl) gcr.getComponent(ProtobufMetadataManager.class).running();
protobufMetadataManager.addProtobufMetadataManagerInterceptor(cr.getComponent(BasicComponentRegistry.class));
}
InternalCacheRegistry icr = gcr.getComponent(InternalCacheRegistry.class).running();
if (!icr.isInternalCache(cacheName)) {
// a stop dependency must be added for each non-internal cache
ProtobufMetadataManagerImpl protobufMetadataManager =
(ProtobufMetadataManagerImpl) gcr.getComponent(ProtobufMetadataManager.class).running();
protobufMetadataManager.addCacheDependency(cacheName);
// a remote query manager must be added for each non-internal cache
SerializationContext serCtx = protobufMetadataManager.getSerializationContext();
RemoteQueryManager remoteQueryManager = buildQueryManager(cfg, serCtx, cr);
cr.registerComponent(remoteQueryManager, RemoteQueryManager.class);
SearchMappingCommonBuilding commonBuilding = cr.getComponent(SearchMappingCommonBuilding.class);
SearchMapping searchMapping = cr.getComponent(SearchMapping.class);
if (commonBuilding != null && searchMapping == null) {
AdvancedCache<?, ?> cache = cr.getComponent(Cache.class).getAdvancedCache().withStorageMediaType()
.withWrapping(ByteArrayWrapper.class, ProtobufWrapper.class);
EntityLoader<?> entityLoader = new EntityLoader<>(cache, queryStatistics);
QueryCache queryCache = cr.getGlobalComponentRegistry().getComponent(QueryCache.class);
searchMapping = new LazySearchMapping(commonBuilding, entityLoader, serCtx, cache, protobufMetadataManager,
queryCache);
cr.registerComponent(searchMapping, SearchMapping.class);
BasicComponentRegistry bcr = cr.getComponent(BasicComponentRegistry.class);
bcr.replaceComponent(IndexStatistics.class.getName(), new LocalIndexStatistics(), true);
bcr.rewire();
}
}
}
private RemoteQueryManager buildQueryManager(Configuration cfg, SerializationContext ctx, ComponentRegistry cr) {
ContentTypeConfiguration valueEncoding = cfg.encoding().valueDataType();
MediaType valueStorageMediaType = valueEncoding.mediaType();
AdvancedCache<?, ?> cache = cr.getComponent(Cache.class).getAdvancedCache();
MediaType storageMediaType = cache.getValueDataConversion().getStorageMediaType();
QuerySerializers querySerializers = buildQuerySerializers(cr, storageMediaType);
boolean isObjectStorage = valueStorageMediaType != null && valueStorageMediaType.match(APPLICATION_OBJECT);
if (isObjectStorage) return new ObjectRemoteQueryManager(cache, cr, querySerializers);
return new ProtobufRemoteQueryManager(cache, cr, ctx, querySerializers);
}
private QuerySerializers buildQuerySerializers(ComponentRegistry cr, MediaType storageMediaType) {
EncoderRegistry encoderRegistry = cr.getGlobalComponentRegistry().getComponent(EncoderRegistry.class);
QuerySerializers querySerializers = new QuerySerializers();
DefaultQuerySerializer defaultQuerySerializer = new DefaultQuerySerializer(encoderRegistry);
querySerializers.addSerializer(MediaType.MATCH_ALL, defaultQuerySerializer);
if (encoderRegistry.isConversionSupported(storageMediaType, APPLICATION_JSON)) {
Transcoder jsonStorage = encoderRegistry.getTranscoder(APPLICATION_JSON, storageMediaType);
querySerializers.addSerializer(APPLICATION_JSON, new JsonQuerySerializer(storageMediaType, jsonStorage));
}
return querySerializers;
}
}
| 11,325
| 55.914573
| 169
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/ObjectProtobufMatcher.java
|
package org.infinispan.query.remote.impl;
import org.infinispan.AdvancedCache;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.objectfilter.impl.MetadataAdapter;
import org.infinispan.objectfilter.impl.ProtobufMatcher;
import org.infinispan.objectfilter.impl.syntax.IndexedFieldProvider;
import org.infinispan.protostream.SerializationContext;
import org.infinispan.protostream.descriptors.Descriptor;
import org.infinispan.protostream.descriptors.FieldDescriptor;
public class ObjectProtobufMatcher extends ProtobufMatcher {
private final AdvancedCache<?, ?> cache;
public ObjectProtobufMatcher(SerializationContext serializationContext, IndexedFieldProvider<Descriptor> indexedFieldProvider,
AdvancedCache<?, ?> cache) {
super(serializationContext, indexedFieldProvider);
this.cache = cache;
}
@Override
protected MetadataAdapter<Descriptor, FieldDescriptor, Integer> createMetadataAdapter(Descriptor messageDescriptor) {
return new ProtobufMetadataProjectableAdapter(super.createMetadataAdapter(messageDescriptor),
cache.withMediaType(MediaType.APPLICATION_PROTOSTREAM, MediaType.APPLICATION_PROTOSTREAM));
}
}
| 1,229
| 42.928571
| 129
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/BaseRemoteQueryManager.java
|
package org.infinispan.query.remote.impl;
import java.util.Map;
import org.infinispan.AdvancedCache;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.encoding.DataConversion;
import org.infinispan.encoding.impl.StorageConfigurationManager;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.marshall.core.EncoderRegistry;
import org.infinispan.query.core.stats.impl.LocalQueryStatistics;
import org.infinispan.query.dsl.Query;
import org.infinispan.query.dsl.QueryResult;
import org.infinispan.query.remote.client.impl.QueryRequest;
import org.infinispan.query.remote.impl.logging.Log;
/**
* @since 9.4
*/
@Scope(Scopes.NAMED_CACHE)
abstract class BaseRemoteQueryManager implements RemoteQueryManager {
private static final Log log = LogFactory.getLog(BaseRemoteQueryManager.class, Log.class);
final AdvancedCache<?, ?> cache;
private final QuerySerializers querySerializers;
private final DataConversion keyDataConversion;
private final DataConversion valueDataConversion;
private final boolean cacheQueryable;
private final MediaType storageType;
private final boolean unknownMediaType;
@Inject protected EncoderRegistry encoderRegistry;
@Inject protected LocalQueryStatistics queryStatistics;
BaseRemoteQueryManager(AdvancedCache<?, ?> cache, QuerySerializers querySerializers, ComponentRegistry cr) {
this.cache = cache;
this.querySerializers = querySerializers;
this.keyDataConversion = cache.getKeyDataConversion();
this.valueDataConversion = cache.getValueDataConversion();
StorageConfigurationManager storageConfigurationManager = cr.getComponent(StorageConfigurationManager.class);
this.storageType = storageConfigurationManager.getValueStorageMediaType();
this.cacheQueryable = storageConfigurationManager.isQueryable();
this.unknownMediaType = storageType.match(MediaType.APPLICATION_UNKNOWN);
}
@Override
public byte[] executeQuery(String queryString, Map<String, Object> namedParametersMap, Integer offset, Integer maxResults,
Integer hitCountAccuracy, AdvancedCache<?, ?> cache, MediaType outputFormat, boolean isLocal) {
if (unknownMediaType) {
log.warnNoMediaType(cache.getName());
} else if (!cacheQueryable) {
throw log.cacheNotQueryable(cache.getName(), storageType.getTypeSubtype());
}
QuerySerializer<?> querySerializer = querySerializers.getSerializer(outputFormat);
Query<Object> query = getQueryEngine(cache).makeQuery(queryString, namedParametersMap, offset, maxResults,
hitCountAccuracy, isLocal);
QueryResult<Object> queryResult = query.execute();
String[] projection = query.getProjection();
RemoteQueryResult remoteQueryResult = new RemoteQueryResult(projection, queryResult.count().value(),
queryResult.count().isExact(), queryResult.list());
Object response = querySerializer.createQueryResponse(remoteQueryResult);
return querySerializer.encodeQueryResponse(response, outputFormat);
}
public Object convertKey(Object key, MediaType destinationFormat) {
return encoderRegistry.convert(key, keyDataConversion.getStorageMediaType(), destinationFormat);
}
public Object convertValue(Object value, MediaType destinationFormat) {
return encoderRegistry.convert(value, valueDataConversion.getStorageMediaType(), destinationFormat);
}
@Override
public QueryRequest decodeQueryRequest(byte[] queryRequest, MediaType requestType) {
return querySerializers.getSerializer(requestType).decodeQueryRequest(queryRequest, requestType);
}
@Override
public DataConversion getKeyDataConversion() {
return keyDataConversion;
}
@Override
public DataConversion getValueDataConversion() {
return valueDataConversion;
}
}
| 4,086
| 42.478723
| 125
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/RemoteQueryEngine.java
|
package org.infinispan.query.remote.impl;
import java.util.Map;
import org.infinispan.AdvancedCache;
import org.infinispan.commons.dataconversion.ByteArrayWrapper;
import org.infinispan.objectfilter.impl.ProtobufMatcher;
import org.infinispan.objectfilter.impl.syntax.parser.IckleParsingResult;
import org.infinispan.protostream.descriptors.Descriptor;
import org.infinispan.query.core.impl.eventfilter.IckleFilterAndConverter;
import org.infinispan.query.dsl.embedded.impl.QueryEngine;
import org.infinispan.query.remote.impl.filter.IckleProtobufFilterAndConverter;
import org.infinispan.util.function.SerializableFunction;
/**
* Same as ObjectRemoteQueryEngine but able to deal with protobuf payloads.
*
* @author anistor@redhat.com
* @since 8.0
*/
final class RemoteQueryEngine extends ObjectRemoteQueryEngine {
private static final SerializableFunction<AdvancedCache<?, ?>, QueryEngine<?>> queryEngineProvider = c -> c.getComponentRegistry().getComponent(RemoteQueryManager.class).getQueryEngine(c);
RemoteQueryEngine(AdvancedCache<?, ?> cache, boolean isIndexed) {
super(isIndexed ? cache.withStorageMediaType().withWrapping(ByteArrayWrapper.class, ProtobufWrapper.class) : cache.withStorageMediaType(), isIndexed, ProtobufMatcher.class);
}
//todo [anistor] null markers and boolean conversions seem to be a thing of the past, might not be needed anymore after the HS6 migration. need to cleanup here!
@Override
protected RowProcessor makeProjectionProcessor(Class<?>[] projectedTypes, Object[] projectedNullMarkers) {
if (projectedNullMarkers != null) {
for (Object projectedNullMarker : projectedNullMarkers) {
if (projectedNullMarker != null) {
return row -> {
for (int i = 0; i < projectedNullMarkers.length; i++) {
if (row[i] != null && row[i].equals(projectedNullMarkers[i])) {
row[i] = null;
}
}
return row;
};
}
}
}
return null;
}
@Override
protected SerializableFunction<AdvancedCache<?, ?>, QueryEngine<?>> getQueryEngineProvider() {
return queryEngineProvider;
}
@Override
protected IckleFilterAndConverter createFilter(String queryString, Map<String, Object> namedParameters) {
return isIndexed ? new IckleProtobufFilterAndConverter(queryString, namedParameters) :
super.createFilter(queryString, namedParameters);
}
@Override
protected Class<?> getTargetedClass(IckleParsingResult<?> parsingResult) {
return byte[].class;
}
@Override
protected String getTargetedNamedType(IckleParsingResult<?> parsingResult) {
Descriptor targetEntityMetadata = (Descriptor) parsingResult.getTargetEntityMetadata();
return targetEntityMetadata.getFullName();
}
}
| 2,894
| 39.774648
| 191
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/ProtobufWrapper.java
|
package org.infinispan.query.remote.impl;
import org.infinispan.commons.dataconversion.Wrapper;
import org.infinispan.commons.dataconversion.WrapperIds;
import org.infinispan.commons.marshall.WrappedByteArray;
import org.infinispan.query.remote.impl.indexing.ProtobufValueWrapper;
/**
* Wraps byte[] in a {@link ProtobufValueWrapper} in order to make the payload indexable by Hibernate Search.
*
* @since 9.1
*/
public final class ProtobufWrapper implements Wrapper {
public static final ProtobufWrapper INSTANCE = new ProtobufWrapper();
private ProtobufWrapper() {
}
@Override
public Object wrap(Object value) {
if (value instanceof byte[]) {
return new ProtobufValueWrapper((byte[]) value);
}
if (value instanceof WrappedByteArray) {
return new ProtobufValueWrapper(((WrappedByteArray) value).getBytes());
}
return value;
}
@Override
public Object unwrap(Object target) {
if (target instanceof ProtobufValueWrapper) {
return ((ProtobufValueWrapper) target).getBinary();
}
if (target instanceof WrappedByteArray) {
return ((WrappedByteArray) target).getBytes();
}
return target;
}
@Override
public byte id() {
return WrapperIds.PROTOBUF_WRAPPER;
}
@Override
public boolean isFilterable() {
return true;
}
}
| 1,373
| 25.423077
| 109
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/indexing/FieldMapping.java
|
package org.infinispan.query.remote.impl.indexing;
import org.infinispan.api.annotations.indexing.option.Structure;
import org.infinispan.api.annotations.indexing.option.TermVector;
import org.infinispan.protostream.descriptors.EnumValueDescriptor;
import org.infinispan.protostream.descriptors.FieldDescriptor;
/**
* A mapping from an object field to an index field and the flags that enable indexing, storage and analysis.
*
* @author anistor@redhat.com
* @since 9.0
*/
public final class FieldMapping {
private final String name;
private final FieldDescriptor fieldDescriptor;
private final boolean searchable;
private final boolean projectable;
private final boolean aggregable;
private final boolean sortable;
private final String analyzer;
private final String normalizer;
private final String indexNullAs;
private final Boolean norms;
private final String searchAnalyzer;
private final TermVector termVector;
private final Integer decimalScale;
private final Integer includeDepth;
private final Structure structure;
/**
* Indicates if lazy initialization of {@link #indexNullAsObj}.
*/
private volatile boolean isInitialized = false;
private Object indexNullAsObj;
public FieldMapping(String name, boolean searchable, boolean projectable, boolean aggregable, boolean sortable,
String analyzer, String normalizer, String indexNullAs, FieldDescriptor fieldDescriptor) {
this(name, searchable, projectable, aggregable, sortable, analyzer, normalizer, indexNullAs,
null, null, null, null, 3, null, fieldDescriptor);
}
public FieldMapping(String name, Boolean searchable, Boolean projectable, Boolean aggregable, Boolean sortable,
String analyzer, String normalizer, String indexNullAs,
Boolean norms, String searchAnalyzer, TermVector termVector, Integer decimalScale,
Integer includeDepth, Structure structure,
FieldDescriptor fieldDescriptor) {
if (name == null) {
throw new IllegalArgumentException("name argument cannot be null");
}
if (fieldDescriptor == null) {
throw new IllegalArgumentException("fieldDescriptor argument cannot be null");
}
this.name = name;
this.fieldDescriptor = fieldDescriptor;
this.searchable = searchable;
this.projectable = projectable;
this.aggregable = aggregable;
this.sortable = sortable;
this.analyzer = analyzer;
this.normalizer = normalizer;
this.indexNullAs = indexNullAs;
this.norms = norms;
this.searchAnalyzer = searchAnalyzer;
this.termVector = termVector;
this.decimalScale = decimalScale;
this.includeDepth = includeDepth;
this.structure = structure;
}
public String name() {
return name;
}
public boolean searchable() {
return searchable;
}
public boolean projectable() {
return projectable;
}
public boolean aggregable() {
return aggregable;
}
public boolean sortable() {
return sortable;
}
public String analyzer() {
return analyzer;
}
public String normalizer() {
return normalizer;
}
public boolean analyzed() {
return analyzer != null;
}
public Object indexNullAs() {
init();
return indexNullAsObj;
}
public Boolean norms() {
return norms;
}
public String searchAnalyzer() {
return searchAnalyzer;
}
public TermVector termVector() {
return termVector;
}
public Integer decimalScale() {
return decimalScale;
}
public Integer includeDepth() {
return includeDepth;
}
public Structure structure() {
return structure;
}
private void init() {
if (!isInitialized) {
if (fieldDescriptor.getType() == null) {
// this could only happen due to a programming error
throw new IllegalStateException("FieldDescriptors are not fully initialised!");
}
indexNullAsObj = parseIndexNullAs();
isInitialized = true;
}
}
public Object parseIndexNullAs() {
if (indexNullAs != null) {
switch (fieldDescriptor.getType()) {
case DOUBLE:
return Double.parseDouble(indexNullAs);
case FLOAT:
return Float.parseFloat(indexNullAs);
case INT64:
case UINT64:
case FIXED64:
case SFIXED64:
case SINT64:
return Long.parseLong(indexNullAs);
case INT32:
case FIXED32:
case UINT32:
case SFIXED32:
case SINT32:
return Integer.parseInt(indexNullAs);
case ENUM:
EnumValueDescriptor enumVal = fieldDescriptor.getEnumType().findValueByName(indexNullAs);
if (enumVal == null) {
throw new IllegalArgumentException("Enum value not found : " + indexNullAs);
}
return enumVal.getNumber();
case BOOL:
return Boolean.valueOf(indexNullAs);
}
}
return indexNullAs;
}
@Override
public String toString() {
return "FieldMapping{" +
"name='" + name + '\'' +
", fieldDescriptor=" + fieldDescriptor +
", searchable=" + searchable +
", projectable=" + projectable +
", aggregable=" + aggregable +
", sortable=" + sortable +
", analyzer='" + analyzer + '\'' +
", normalizer='" + normalizer + '\'' +
", indexNullAs='" + indexNullAs + '\'' +
", norms=" + norms +
", searchAnalyzer='" + searchAnalyzer + '\'' +
", termVector=" + termVector +
", decimalScale=" + decimalScale +
", includeDepth=" + includeDepth +
", structure=" + structure +
'}';
}
}
| 6,044
| 29.376884
| 114
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/indexing/ProtobufValueWrapper.java
|
package org.infinispan.query.remote.impl.indexing;
import java.util.Arrays;
import org.infinispan.commons.marshall.ProtoStreamTypeIds;
import org.infinispan.commons.marshall.WrappedBytes;
import org.infinispan.protostream.annotations.ProtoFactory;
import org.infinispan.protostream.annotations.ProtoField;
import org.infinispan.protostream.annotations.ProtoTypeId;
import org.infinispan.protostream.descriptors.Descriptor;
import org.infinispan.query.remote.impl.mapping.typebridge.ProtobufMessageBridge;
/**
* This is used to wrap binary values encoded with Protocol Buffers. {@link ProtobufMessageBridge} is used as
* a class bridge to allow indexing of the binary payload.
*
* @author anistor@redhat.com
* @since 6.0
*/
@ProtoTypeId(ProtoStreamTypeIds.PROTOBUF_VALUE_WRAPPER)
public final class ProtobufValueWrapper implements WrappedBytes {
/**
* Max number of bytes to include in {@link #toString()}.
*/
private static final int MAX_BYTES_IN_TOSTRING = 40;
/**
* The protobuf encoded payload.
*/
private final byte[] binary;
/**
* The lazily computed hashCode. Transient field!
*/
private transient int hashCode = 0;
/**
* The Descriptor of the message (if it's a Message and not a primitive value, or null otherwise). Transient field!
*/
private transient Descriptor messageDescriptor;
@ProtoFactory
public ProtobufValueWrapper(byte[] binary) {
if (binary == null) {
throw new IllegalArgumentException("argument cannot be null");
}
this.binary = binary;
}
/**
* Gets the internal byte array. Callers should not modify the contents of the array.
*
* @return the wrapped byte array
*/
@ProtoField(number = 1)
public byte[] getBinary() {
return binary;
}
/**
* Returns the Protobuf descriptor of the message type of the payload.
*
* @see #setMessageDescriptor
*/
public Descriptor getMessageDescriptor() {
return messageDescriptor;
}
/**
* Sets the Protobuf descriptor of the message type of the payload.
*/
void setMessageDescriptor(Descriptor messageDescriptor) {
this.messageDescriptor = messageDescriptor;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ProtobufValueWrapper that = (ProtobufValueWrapper) o;
return Arrays.equals(binary, that.binary);
}
@Override
public int hashCode() {
if (hashCode == 0) {
hashCode = Arrays.hashCode(binary);
}
return hashCode;
}
@Override
public String toString() {
// Render only max 40 bytes
int len = Math.min(binary.length, MAX_BYTES_IN_TOSTRING);
StringBuilder sb = new StringBuilder(50 + 3 * len);
sb.append("ProtobufValueWrapper(length=").append(binary.length).append(", binary=[");
for (int i = 0; i < len; i++) {
if (i != 0) {
sb.append(' ');
}
sb.append(String.format("%02X", binary[i] & 0xff));
}
if (len < binary.length) {
sb.append("...");
}
sb.append("])");
return sb.toString();
}
@Override
public byte[] getBytes() {
return binary;
}
@Override
public int backArrayOffset() {
return 0;
}
@Override
public int getLength() {
return binary.length;
}
@Override
public byte getByte(int offset) {
return binary[offset];
}
@Override
public boolean equalsWrappedBytes(WrappedBytes other) {
if (other == null) return false;
if (other.getLength() != binary.length) return false;
for (int i = 0; i < binary.length; ++i) {
if (binary[i] != other.getByte(i)) return false;
}
return true;
}
}
| 3,822
| 25.734266
| 118
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/indexing/IndexingMetadata.java
|
package org.infinispan.query.remote.impl.indexing;
import java.util.Map;
import org.infinispan.protostream.descriptors.AnnotationElement;
import org.infinispan.protostream.descriptors.Descriptor;
/**
* @author anistor@redhat.com
* @since 7.0
*/
public final class IndexingMetadata {
public static final String INDEXED_ANNOTATION = "Indexed";
public static final String INDEXED_INDEX_ATTRIBUTE = "index";
public static final String YES = "YES";
public static final String NO = "NO";
/**
* Indicates if the type is indexed.
*/
private final boolean isIndexed;
/**
* The name of the index. Can be {@code null}.
*/
private final String indexName;
/**
* The name of the analyzer. Can be {@code null}.
*/
private final String analyzer;
/**
* Field mappings. This is null if indexing is disabled.
*/
private final Map<String, FieldMapping> fields;
public IndexingMetadata(boolean isIndexed, String indexName, String analyzer, Map<String, FieldMapping> fields) {
this.isIndexed = isIndexed;
this.indexName = indexName;
this.analyzer = analyzer;
this.fields = fields;
}
public boolean isIndexed() {
return isIndexed;
}
// TODO [anistor] The index name is ignored for now because all types get indexed in the same index of ProtobufValueWrapper
public String indexName() {
return indexName;
}
public String analyzer() {
return analyzer;
}
public boolean isFieldSearchable(String fieldName) {
if (fields == null) {
return isIndexed;
}
FieldMapping fieldMapping = fields.get(fieldName);
return fieldMapping != null && fieldMapping.searchable();
}
public boolean isFieldAnalyzed(String fieldName) {
if (fields == null) {
return false;
}
FieldMapping fieldMapping = fields.get(fieldName);
return fieldMapping != null && fieldMapping.analyzed();
}
public boolean isFieldProjectable(String fieldName) {
if (fields == null) {
return isIndexed;
}
FieldMapping fieldMapping = fields.get(fieldName);
return fieldMapping != null && fieldMapping.projectable();
}
public boolean isFieldSortable(String fieldName) {
if (fields == null) {
return isIndexed;
}
FieldMapping fieldMapping = fields.get(fieldName);
return fieldMapping != null && fieldMapping.sortable();
}
public Object getNullMarker(String fieldName) {
if (fields == null) {
return null;
}
FieldMapping fieldMapping = fields.get(fieldName);
return fieldMapping != null ? fieldMapping.indexNullAs() : null;
}
public FieldMapping getFieldMapping(String name) {
if (fields == null) {
return null;
}
return fields.get(name);
}
@Override
public String toString() {
return "IndexingMetadata{" +
"isIndexed=" + isIndexed +
", indexName='" + indexName + '\'' +
", analyzer='" + analyzer + '\'' +
", fields=" + fields +
'}';
}
public static AnnotationElement.Annotation findAnnotation(Map<String, AnnotationElement.Annotation> annotations, String name) {
return annotations.get(name);
}
public static <T> T findProcessedAnnotation(Descriptor descriptor, String name) {
return descriptor.getProcessedAnnotation(name);
}
public static boolean attributeMatches(AnnotationElement.Value attr, String packageName, String... validValues) {
String v = String.valueOf(attr.getValue());
for(String valid : validValues) {
if (valid.equals(v) || (packageName+'.'+valid).equals(v)) {
return true;
}
}
return false;
}
}
| 3,784
| 27.037037
| 130
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/indexing/IndexingTagHandler.java
|
package org.infinispan.query.remote.impl.indexing;
import org.hibernate.search.engine.backend.document.DocumentElement;
import org.hibernate.search.engine.backend.document.IndexFieldReference;
import org.hibernate.search.engine.backend.document.IndexObjectFieldReference;
import org.infinispan.protostream.TagHandler;
import org.infinispan.protostream.descriptors.Descriptor;
import org.infinispan.protostream.descriptors.FieldDescriptor;
import org.infinispan.query.remote.impl.indexing.aggregator.BigDecimalAggregator;
import org.infinispan.query.remote.impl.indexing.aggregator.BigIntegerAggregator;
import org.infinispan.query.remote.impl.indexing.aggregator.TypeAggregator;
import org.infinispan.query.remote.impl.mapping.reference.FieldReferenceProvider;
import org.infinispan.query.remote.impl.mapping.reference.IndexReferenceHolder;
/**
* Extracts and indexes all tags (fields) from a protobuf encoded message.
*
* @author anistor@redhat.com
* @since 6.0
*/
public final class IndexingTagHandler implements TagHandler {
private final IndexReferenceHolder indexReferenceHolder;
private IndexingMessageContext messageContext;
public IndexingTagHandler(Descriptor messageDescriptor, DocumentElement document, IndexReferenceHolder indexReferenceHolder) {
this.indexReferenceHolder = indexReferenceHolder;
this.messageContext = new IndexingMessageContext(null, null, messageDescriptor, document, null);
}
@Override
public void onTag(int fieldNumber, FieldDescriptor fieldDescriptor, Object tagValue) {
messageContext.markField(fieldNumber);
if (fieldDescriptor == null) {
// Unknown fields are not indexed.
return;
}
TypeAggregator typeAggregator = messageContext.getTypeAggregator();
if (typeAggregator != null) {
typeAggregator.add(fieldDescriptor, tagValue);
return;
}
addFieldToDocument(fieldDescriptor, tagValue);
}
private void addFieldToDocument(FieldDescriptor fieldDescriptor, Object value) {
// We always use fully qualified field names because Lucene does not allow two identically named fields defined by
// different entity types to have different field types or different indexing options in the same index.
String fieldPath = messageContext.getFieldPath();
fieldPath = fieldPath != null ? fieldPath + '.' + fieldDescriptor.getName() : fieldDescriptor.getName();
IndexFieldReference<?> fieldReference = indexReferenceHolder.getFieldReference(fieldPath);
if (fieldReference != null) {
messageContext.addValue(fieldReference, value);
}
}
@Override
public void onStartNested(int fieldNumber, FieldDescriptor fieldDescriptor) {
messageContext.markField(fieldNumber);
pushContext(fieldDescriptor, fieldDescriptor.getMessageType());
}
@Override
public void onEndNested(int fieldNumber, FieldDescriptor fieldDescriptor) {
popContext();
}
@Override
public void onEnd() {
indexMissingFields();
}
private void pushContext(FieldDescriptor fieldDescriptor, Descriptor messageDescriptor) {
String fieldPath = messageContext.getFieldPath();
fieldPath = fieldPath != null ? fieldPath + '.' + fieldDescriptor.getName() : fieldDescriptor.getName();
IndexFieldReference<?> messageField = indexReferenceHolder.getFieldReference(fieldPath);
if (messageField != null) {
if (pushMessageFieldContext(fieldDescriptor, messageDescriptor, messageField)) {
return;
}
}
DocumentElement documentElement = null;
if (messageContext.getDocument() != null) {
IndexObjectFieldReference objectReference = indexReferenceHolder.getObjectReference(fieldPath);
if (objectReference != null) {
documentElement = messageContext.getDocument().addObject(objectReference);
}
}
messageContext = new IndexingMessageContext(messageContext, fieldDescriptor, messageDescriptor, documentElement, null);
}
private boolean pushMessageFieldContext(FieldDescriptor fieldDescriptor, Descriptor messageDescriptor,
IndexFieldReference<?> messageField) {
String fullName = messageDescriptor.getFullName();
if (FieldReferenceProvider.BIG_INTEGER_COMMON_TYPE.equals(fullName)) {
messageContext = new IndexingMessageContext(messageContext, fieldDescriptor, messageDescriptor,
messageContext.getDocument(), new BigIntegerAggregator(messageField));
return true;
}
if (FieldReferenceProvider.BIG_DECIMAL_COMMON_TYPE.equals(fullName)) {
messageContext = new IndexingMessageContext(messageContext, fieldDescriptor, messageDescriptor,
messageContext.getDocument(), new BigDecimalAggregator(messageField));
return true;
}
return false;
}
private void popContext() {
TypeAggregator typeAggregator = messageContext.getTypeAggregator();
if (typeAggregator != null) {
typeAggregator.addValue(messageContext);
} else {
indexMissingFields();
}
messageContext = messageContext.getParentContext();
}
/**
* All fields that were not seen until the end of this message are missing and will be indexed with their default
* value or null if none was declared. The null value is replaced with a special null token placeholder because
* Lucene cannot index nulls.
*/
private void indexMissingFields() {
if (messageContext.getDocument() == null) {
return;
}
for (FieldDescriptor fieldDescriptor : messageContext.getMessageDescriptor().getFields()) {
if (!messageContext.isFieldMarked(fieldDescriptor.getNumber())) {
Object defaultValue = fieldDescriptor.hasDefaultValue() ? fieldDescriptor.getDefaultValue() : null;
addFieldToDocument(fieldDescriptor, defaultValue);
}
}
}
}
| 5,987
| 40.583333
| 129
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/indexing/WrappedMessageTagHandler.java
|
package org.infinispan.query.remote.impl.indexing;
import org.infinispan.protostream.SerializationContext;
import org.infinispan.protostream.TagHandler;
import org.infinispan.protostream.WrappedMessage;
import org.infinispan.protostream.descriptors.Descriptor;
import org.infinispan.protostream.descriptors.FieldDescriptor;
import org.infinispan.protostream.descriptors.GenericDescriptor;
/**
* Protostream tag handler for {@code org.infinispan.protostream.WrappedMessage} protobuf type defined in
* message-wrapping.proto. This handler extracts the embedded value or message but does not parse the message, it just
* discovers its type.
*
* @author anistor@redhat.com
* @since 6.0
*/
class WrappedMessageTagHandler implements TagHandler {
protected final ProtobufValueWrapper valueWrapper;
protected final SerializationContext serCtx;
protected GenericDescriptor descriptor;
protected byte[] messageBytes;
protected Number numericValue;
protected String stringValue;
WrappedMessageTagHandler(ProtobufValueWrapper valueWrapper, SerializationContext serCtx) {
this.valueWrapper = valueWrapper;
this.serCtx = serCtx;
}
@Override
public void onStart(GenericDescriptor descriptor) {
}
@Override
public void onTag(int fieldNumber, FieldDescriptor fieldDescriptor, Object value) {
switch (fieldNumber) {
case WrappedMessage.WRAPPED_BOOL:
stringValue = value != null ? value.toString() : null;
break;
case WrappedMessage.WRAPPED_BYTES:
case WrappedMessage.WRAPPED_STRING:
stringValue = (String) value;
break;
case WrappedMessage.WRAPPED_ENUM:
case WrappedMessage.WRAPPED_DOUBLE:
case WrappedMessage.WRAPPED_FLOAT:
case WrappedMessage.WRAPPED_INT64:
case WrappedMessage.WRAPPED_INT32:
case WrappedMessage.WRAPPED_FIXED64:
case WrappedMessage.WRAPPED_FIXED32:
case WrappedMessage.WRAPPED_UINT32:
case WrappedMessage.WRAPPED_SFIXED32:
case WrappedMessage.WRAPPED_SFIXED64:
case WrappedMessage.WRAPPED_SINT32:
case WrappedMessage.WRAPPED_SINT64:
numericValue = (Number) value;
break;
case WrappedMessage.WRAPPED_DESCRIPTOR_FULL_NAME: {
String typeName = (String) value;
descriptor = serCtx.getDescriptorByName(typeName);
break;
}
case WrappedMessage.WRAPPED_DESCRIPTOR_TYPE_ID: {
Integer typeId = (Integer) value;
descriptor = serCtx.getDescriptorByTypeId(typeId);
break;
}
case WrappedMessage.WRAPPED_MESSAGE:
messageBytes = (byte[]) value;
break;
default:
throw new IllegalStateException("Unexpected field : " + fieldNumber);
}
}
@Override
public void onStartNested(int fieldNumber, FieldDescriptor fieldDescriptor) {
throw new IllegalStateException("Invalid WrappedMessage! Nested messages are not expected.");
}
@Override
public void onEndNested(int fieldNumber, FieldDescriptor fieldDescriptor) {
throw new IllegalStateException("Invalid WrappedMessage! Nested messages are not expected.");
}
@Override
public void onEnd() {
if (messageBytes != null) {
// it's a message, not a primitive value; we must have a type now
if (descriptor == null) {
throw new IllegalStateException("Invalid WrappedMessage! Either type name or type id fields must be present but none was encountered.");
}
valueWrapper.setMessageDescriptor((Descriptor) descriptor);
}
}
public byte[] getMessageBytes() {
return messageBytes;
}
}
| 3,766
| 34.87619
| 148
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/indexing/ProtobufEntityConverter.java
|
package org.infinispan.query.remote.impl.indexing;
import java.io.IOException;
import java.util.Set;
import java.util.stream.Collectors;
import org.hibernate.search.mapper.pojo.model.spi.PojoRawTypeIdentifier;
import org.infinispan.commons.CacheException;
import org.infinispan.protostream.ProtobufParser;
import org.infinispan.protostream.SerializationContext;
import org.infinispan.protostream.WrappedMessage;
import org.infinispan.protostream.descriptors.Descriptor;
import org.infinispan.query.remote.impl.mapping.reference.GlobalReferenceHolder;
import org.infinispan.search.mapper.mapping.EntityConverter;
public class ProtobufEntityConverter implements EntityConverter {
private final static PojoRawTypeIdentifier<byte[]> BYTE_ARRAY_TYPE_IDENTIFIER = PojoRawTypeIdentifier.of(byte[].class);
private final SerializationContext serializationContext;
private final Set<String> indexedMessageTypes;
public ProtobufEntityConverter(SerializationContext serializationContext, Set<GlobalReferenceHolder.RootMessageInfo> rootMessages) {
this.serializationContext = serializationContext;
this.indexedMessageTypes = rootMessages.stream().map(rootMessage -> rootMessage.getFullName()).collect(Collectors.toSet());
}
@Override
public Class<?> targetType() {
return ProtobufValueWrapper.class;
}
@Override
public PojoRawTypeIdentifier<?> convertedTypeIdentifier() {
return BYTE_ARRAY_TYPE_IDENTIFIER;
}
@Override
public ConvertedEntity convert(Object entity) {
ProtobufValueWrapper valueWrapper = (ProtobufValueWrapper) entity;
WrappedMessageTagHandler tagHandler = new WrappedMessageTagHandler(valueWrapper, serializationContext);
try {
Descriptor wrapperDescriptor = serializationContext.getMessageDescriptor(WrappedMessage.PROTOBUF_TYPE_NAME);
ProtobufParser.INSTANCE.parse(tagHandler, wrapperDescriptor, valueWrapper.getBinary());
} catch (IOException e) {
throw new CacheException(e);
}
Descriptor messageDescriptor = valueWrapper.getMessageDescriptor();
if (messageDescriptor == null) {
return new ProtobufConvertedEntity(true, null, null);
}
String entityName = messageDescriptor.getFullName();
boolean skip = !indexedMessageTypes.contains(entityName);
byte[] messageBytes = tagHandler.getMessageBytes();
return new ProtobufConvertedEntity(skip, entityName, messageBytes);
}
private static class ProtobufConvertedEntity implements ConvertedEntity {
private final boolean skip;
private final String entityName;
private final byte[] value;
public ProtobufConvertedEntity(boolean skip, String entityName, byte[] value) {
this.skip = skip;
this.entityName = entityName;
this.value = value;
}
@Override
public boolean skip() {
return skip;
}
@Override
public String entityName() {
return entityName;
}
@Override
public Object value() {
return value;
}
}
}
| 3,086
| 34.079545
| 135
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/indexing/IndexingMessageContext.java
|
package org.infinispan.query.remote.impl.indexing;
import org.hibernate.search.engine.backend.document.DocumentElement;
import org.hibernate.search.engine.backend.document.IndexFieldReference;
import org.infinispan.protostream.MessageContext;
import org.infinispan.protostream.descriptors.Descriptor;
import org.infinispan.protostream.descriptors.FieldDescriptor;
import org.infinispan.query.remote.impl.indexing.aggregator.TypeAggregator;
public final class IndexingMessageContext extends MessageContext<IndexingMessageContext> {
// null if the embedded is not indexed
private final DocumentElement document;
private final TypeAggregator typeAggregator;
public IndexingMessageContext(IndexingMessageContext parentContext, FieldDescriptor fieldDescriptor,
Descriptor messageDescriptor, DocumentElement document,
TypeAggregator typeAggregator) {
super(parentContext, fieldDescriptor, messageDescriptor);
this.document = document;
this.typeAggregator = typeAggregator;
}
public DocumentElement getDocument() {
return document;
}
public TypeAggregator getTypeAggregator() {
return typeAggregator;
}
public void addValue(IndexFieldReference fieldReference, Object value) {
if (document != null) {
// using raw type for IndexFieldReference
// value type and fieldReference value type are supposed to match
document.addValue(fieldReference, value);
}
}
}
| 1,524
| 37.125
| 103
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/indexing/search5/Search5MetadataCreator.java
|
package org.infinispan.query.remote.impl.indexing.search5;
import static org.infinispan.query.remote.impl.indexing.IndexingMetadata.findAnnotation;
import java.util.HashMap;
import java.util.Map;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.protostream.AnnotationMetadataCreator;
import org.infinispan.protostream.descriptors.AnnotationElement;
import org.infinispan.protostream.descriptors.Descriptor;
import org.infinispan.protostream.descriptors.FieldDescriptor;
import org.infinispan.protostream.descriptors.Type;
import org.infinispan.query.remote.impl.indexing.FieldMapping;
import org.infinispan.query.remote.impl.indexing.IndexingMetadata;
import org.infinispan.query.remote.impl.indexing.infinispan.InfinispanAnnotations;
import org.infinispan.query.remote.impl.indexing.infinispan.InfinispanMetadataCreator;
import org.infinispan.query.remote.impl.logging.Log;
import org.infinispan.search.mapper.mapping.impl.DefaultAnalysisConfigurer;
//todo [anistor] Should be able to have multiple mappings per field like in Hibernate Search, ie. have a @Fields plural annotation
/**
* {@link AnnotationMetadataCreator} for {@code @Indexed} ProtoStream annotation placed at message type level. Also
* handles {@code @Field} and {@code @SortableField} and {@code @Analyzer} annotations placed at field level.
*
* @author anistor@redhat.com
* @since 7.0
*/
final class Search5MetadataCreator implements AnnotationMetadataCreator<IndexingMetadata, Descriptor> {
private static final Log log = LogFactory.getLog(Search5MetadataCreator.class, Log.class);
@Override
public IndexingMetadata create(Descriptor descriptor, AnnotationElement.Annotation annotation) {
Boolean enabled = (Boolean) annotation.getAttributeValue(InfinispanAnnotations.ENABLED_ATTRIBUTE).getValue();
String indexName = (String) annotation.getAttributeValue(IndexingMetadata.INDEXED_INDEX_ATTRIBUTE).getValue();
if (indexName.isEmpty()) {
indexName = null;
}
String entityAnalyzer = null;
AnnotationElement.Annotation entityAnalyzerAnnotation = findAnnotation(descriptor.getAnnotations(), Search5Annotations.ANALYZER_ANNOTATION);
if (entityAnalyzerAnnotation != null) {
String v = (String) entityAnalyzerAnnotation.getAttributeValue(Search5Annotations.ANALYZER_DEFINITION_ATTRIBUTE).getValue();
if (!v.isEmpty()) {
entityAnalyzer = v;
}
}
Map<String, FieldMapping> fields = new HashMap<>(descriptor.getFields().size());
for (FieldDescriptor fd : descriptor.getFields()) {
Map<String, AnnotationElement.Annotation> annotations = fd.getAnnotations();
FieldMapping fieldMapping = InfinispanMetadataCreator.fieldMapping(fd, annotations);
if (fieldMapping != null) {
fields.put(fd.getName(), fieldMapping);
continue;
}
fieldMapping = search5FieldMapping(fd, annotations);
if (fieldMapping != null) {
fields.put(fd.getName(), fieldMapping);
}
}
IndexingMetadata indexingMetadata = new IndexingMetadata(enabled, indexName, entityAnalyzer, fields);
if (log.isDebugEnabled()) {
log.debugf("Descriptor name=%s indexingMetadata=%s", descriptor.getFullName(), indexingMetadata);
}
return indexingMetadata;
}
private static FieldMapping search5FieldMapping(FieldDescriptor fd, Map<String, AnnotationElement.Annotation> annotations) {
String fieldLevelAnalyzer = null;
AnnotationElement.Annotation fieldAnalyzerAnnotation = findAnnotation(fd.getAnnotations(), Search5Annotations.ANALYZER_ANNOTATION);
if (fieldAnalyzerAnnotation != null) {
String v = (String) fieldAnalyzerAnnotation.getAttributeValue(Search5Annotations.ANALYZER_DEFINITION_ATTRIBUTE).getValue();
if (!v.isEmpty()) {
fieldLevelAnalyzer = v;
}
}
boolean isSortable = findAnnotation(fd.getAnnotations(), Search5Annotations.SORTABLE_FIELD_ANNOTATION) != null;
AnnotationElement.Annotation fieldAnnotation = findAnnotation(fd.getAnnotations(), Search5Annotations.FIELD_ANNOTATION);
if (fieldAnnotation == null) {
return null;
}
String fieldName = fd.getName();
String v = (String) fieldAnnotation.getAttributeValue(Search5Annotations.FIELD_NAME_ATTRIBUTE).getValue();
if (!v.isEmpty()) {
fieldName = v;
}
AnnotationElement.Value indexAttribute = fieldAnnotation.getAttributeValue(Search5Annotations.FIELD_INDEX_ATTRIBUTE);
boolean isIndexed = IndexingMetadata.attributeMatches(indexAttribute, Search5Annotations.LEGACY_ANNOTATION_PACKAGE, Search5Annotations.INDEX_YES, IndexingMetadata.YES);
AnnotationElement.Value analyzeAttribute = fieldAnnotation.getAttributeValue(Search5Annotations.FIELD_ANALYZE_ATTRIBUTE);
boolean isAnalyzed = IndexingMetadata.attributeMatches(analyzeAttribute, Search5Annotations.LEGACY_ANNOTATION_PACKAGE, Search5Annotations.ANALYZE_YES, IndexingMetadata.YES);
AnnotationElement.Value storeAttribute = fieldAnnotation.getAttributeValue(Search5Annotations.FIELD_STORE_ATTRIBUTE);
boolean isStored = IndexingMetadata.attributeMatches(storeAttribute, Search5Annotations.LEGACY_ANNOTATION_PACKAGE, Search5Annotations.STORE_YES, IndexingMetadata.YES);
AnnotationElement.Value indexNullAsAttribute = fieldAnnotation.getAttributeValue(Search5Annotations.FIELD_INDEX_NULL_AS_ATTRIBUTE);
String indexNullAs = (String) indexNullAsAttribute.getValue();
if (Search5Annotations.DO_NOT_INDEX_NULL.equals(indexNullAs)) {
indexNullAs = null;
}
AnnotationElement.Annotation fieldLevelAnalyzerAnnotationAttribute = (AnnotationElement.Annotation) fieldAnnotation.getAttributeValue(Search5Annotations.FIELD_ANALYZER_ATTRIBUTE).getValue();
String fieldLevelAnalyzerAttribute = (String) fieldLevelAnalyzerAnnotationAttribute.getAttributeValue(Search5Annotations.ANALYZER_DEFINITION_ATTRIBUTE).getValue();
if (fieldLevelAnalyzerAttribute.isEmpty()) {
fieldLevelAnalyzerAttribute = null;
} else {
// TODO [anistor] field level analyzer attribute overrides the one specified by an eventual field level Analyzer annotation. Need to check if this is consistent with hibernate search
fieldLevelAnalyzer = fieldLevelAnalyzerAttribute;
}
// field level analyzer should not be specified unless the field is analyzed
if (!isAnalyzed && (fieldLevelAnalyzer != null || fieldLevelAnalyzerAttribute != null)) {
throw new IllegalStateException("Cannot specify an analyzer for field " + fd.getFullName() + " unless the field is analyzed.");
}
String analyzer = analyzer(fd.getType(), isAnalyzed, fieldLevelAnalyzer);
FieldMapping fieldMapping = new FieldMapping(
fieldName,
isIndexed, isStored, false, sortable(analyzer, isStored, isSortable),
analyzer, null, indexNullAs, fd);
if (log.isDebugEnabled()) {
log.debugf("fieldName=%s fieldMapping=%s", fieldName, fieldMapping);
}
return fieldMapping;
}
private static boolean sortable(String fieldLevelAnalyzer, boolean isStored, boolean isSortable) {
if (fieldLevelAnalyzer != null) {
return false;
}
return (isSortable || isStored);
}
private static String analyzer(Type type, boolean analyze, String fieldLevelAnalyzer) {
if (!Type.STRING.equals(type) || !analyze) {
return null;
}
return (fieldLevelAnalyzer != null) ? fieldLevelAnalyzer :
DefaultAnalysisConfigurer.STANDARD_ANALYZER_NAME;
}
}
| 7,709
| 48.10828
| 196
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/indexing/search5/Search5Annotations.java
|
package org.infinispan.query.remote.impl.indexing.search5;
import org.infinispan.protostream.config.Configuration;
import org.infinispan.protostream.descriptors.AnnotationElement;
import org.infinispan.query.remote.impl.indexing.IndexingMetadata;
import org.infinispan.query.remote.impl.indexing.infinispan.InfinispanAnnotations;
public final class Search5Annotations {
public static final String LEGACY_ANNOTATION_PACKAGE = "org.hibernate.search.annotations";
/**
* Similar to org.hibernate.search.annotations.Fields/Field.
*/
public static final String FIELDS_ANNOTATION = "Fields";
public static final String FIELD_ANNOTATION = "Field";
public static final String FIELD_NAME_ATTRIBUTE = "name";
public static final String FIELD_INDEX_ATTRIBUTE = "index";
public static final String FIELD_ANALYZE_ATTRIBUTE = "analyze";
public static final String FIELD_STORE_ATTRIBUTE = "store";
public static final String FIELD_ANALYZER_ATTRIBUTE = "analyzer";
public static final String FIELD_INDEX_NULL_AS_ATTRIBUTE = "indexNullAs";
public static final String INDEX_YES = "Index.YES";
public static final String INDEX_NO = "Index.NO";
public static final String ANALYZE_YES = "Analyze.YES";
public static final String ANALYZE_NO = "Analyze.NO";
public static final String STORE_YES = "Store.YES";
public static final String STORE_NO = "Store.NO";
/**
* A marker value that indicates nulls should not be indexed.
*/
public static final String DO_NOT_INDEX_NULL = "__DO_NOT_INDEX_NULL__";
/**
* Similar to org.hibernate.search.annotations.Analyzer. Can be placed at both message and field level.
*/
public static final String ANALYZER_ANNOTATION = "Analyzer";
public static final String ANALYZER_DEFINITION_ATTRIBUTE = "definition";
public static final String SORTABLE_FIELD_ANNOTATION = "SortableField";
public static final String SORTABLE_FIELDS_ANNOTATION = "SortableFields";
public static void configure(Configuration.Builder builder) {
builder.annotationsConfig()
.annotation(IndexingMetadata.INDEXED_ANNOTATION, AnnotationElement.AnnotationTarget.MESSAGE)
.packageName(LEGACY_ANNOTATION_PACKAGE)
.attribute(IndexingMetadata.INDEXED_INDEX_ATTRIBUTE)
.type(AnnotationElement.AttributeType.STRING)
.defaultValue("")
.attribute(InfinispanAnnotations.ENABLED_ATTRIBUTE)
.type(AnnotationElement.AttributeType.BOOLEAN)
.defaultValue(true)
.metadataCreator(new Search5MetadataCreator())
.annotation(ANALYZER_ANNOTATION, AnnotationElement.AnnotationTarget.MESSAGE, AnnotationElement.AnnotationTarget.FIELD)
.packageName(LEGACY_ANNOTATION_PACKAGE)
.attribute(ANALYZER_DEFINITION_ATTRIBUTE)
.type(AnnotationElement.AttributeType.STRING)
.defaultValue("")
.annotation(FIELD_ANNOTATION, AnnotationElement.AnnotationTarget.FIELD)
.packageName(LEGACY_ANNOTATION_PACKAGE)
.repeatable(FIELDS_ANNOTATION)
.attribute(FIELD_NAME_ATTRIBUTE)
.type(AnnotationElement.AttributeType.STRING)
.defaultValue("")
.attribute(FIELD_INDEX_ATTRIBUTE)
.type(AnnotationElement.AttributeType.IDENTIFIER)
.packageName(LEGACY_ANNOTATION_PACKAGE)
.allowedValues(INDEX_YES, INDEX_NO, IndexingMetadata.YES, IndexingMetadata.NO)
.defaultValue(INDEX_YES)
.attribute(FIELD_ANALYZE_ATTRIBUTE)
.type(AnnotationElement.AttributeType.IDENTIFIER)
.packageName(LEGACY_ANNOTATION_PACKAGE)
.allowedValues(ANALYZE_YES, ANALYZE_NO, IndexingMetadata.YES, IndexingMetadata.NO)
.defaultValue(ANALYZE_NO) //NOTE: this differs from Hibernate Search's default which is Analyze.YES !
.attribute(FIELD_STORE_ATTRIBUTE)
.type(AnnotationElement.AttributeType.IDENTIFIER)
.packageName(LEGACY_ANNOTATION_PACKAGE)
.allowedValues(STORE_YES, STORE_NO, IndexingMetadata.YES, IndexingMetadata.NO)
.defaultValue(STORE_NO)
.attribute(FIELD_ANALYZER_ATTRIBUTE)
.type(AnnotationElement.AttributeType.ANNOTATION)
.allowedValues(ANALYZER_ANNOTATION)
.defaultValue("@Analyzer(definition=\"\")")
.attribute(FIELD_INDEX_NULL_AS_ATTRIBUTE)
.type(AnnotationElement.AttributeType.STRING)
.defaultValue(DO_NOT_INDEX_NULL)
.annotation(SORTABLE_FIELD_ANNOTATION, AnnotationElement.AnnotationTarget.FIELD)
.packageName(LEGACY_ANNOTATION_PACKAGE)
.repeatable(SORTABLE_FIELDS_ANNOTATION);
}
}
| 4,955
| 50.625
| 130
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/indexing/infinispan/InfinispanAnnotations.java
|
package org.infinispan.query.remote.impl.indexing.infinispan;
import java.util.ArrayList;
import org.infinispan.api.annotations.indexing.model.Values;
import org.infinispan.api.annotations.indexing.option.Structure;
import org.infinispan.api.annotations.indexing.option.TermVector;
import org.infinispan.protostream.config.Configuration;
import org.infinispan.protostream.descriptors.AnnotationElement;
public class InfinispanAnnotations {
public static final String ANNOTATIONS_OPTIONS_PACKAGE = "org.infinispan.api.annotations.indexing.option";
public static final String ENABLED_ATTRIBUTE = "enabled";
public static final String BASIC_ANNOTATION = "Basic";
public static final String NAME_ATTRIBUTE = "name";
public static final String SEARCHABLE_ATTRIBUTE = "searchable";
public static final String PROJECTABLE_ATTRIBUTE = "projectable";
public static final String AGGREGABLE_ATTRIBUTE = "aggregable";
public static final String SORTABLE_ATTRIBUTE = "sortable";
public static final String INDEX_NULL_AS_ATTRIBUTE = "indexNullAs";
public static final String KEYWORD_ANNOTATION = "Keyword";
public static final String TEXT_ANNOTATION = "Text";
public static final String NORMALIZER_ATTRIBUTE = "normalizer";
public static final String ANALYZER_ATTRIBUTE = "analyzer";
public static final String SEARCH_ANALYZER_ATTRIBUTE = "searchAnalyzer";
public static final String NORMS_ATTRIBUTE = "norms";
public static final String TERM_VECTOR_ATTRIBUTE = "termVector";
public static final String DECIMAL_ANNOTATION = "Decimal";
public static final String DECIMAL_SCALE_ATTRIBUTE = "decimalScale";
public static final String EMBEDDED_ANNOTATION = "Embedded";
public static final String INCLUDE_DEPTH_ATTRIBUTE = "includeDepth";
public static final String STRUCTURE_ATTRIBUTE = "structure";
public static void configure(Configuration.Builder builder) {
builder.annotationsConfig()
.annotation(BASIC_ANNOTATION, AnnotationElement.AnnotationTarget.FIELD)
.attribute(NAME_ATTRIBUTE)
.type(AnnotationElement.AttributeType.STRING)
.defaultValue("")
.attribute(SEARCHABLE_ATTRIBUTE)
.type(AnnotationElement.AttributeType.BOOLEAN)
.defaultValue(true)
.attribute(PROJECTABLE_ATTRIBUTE)
.type(AnnotationElement.AttributeType.BOOLEAN)
.defaultValue(false)
.attribute(AGGREGABLE_ATTRIBUTE)
.type(AnnotationElement.AttributeType.BOOLEAN)
.defaultValue(false)
.attribute(SORTABLE_ATTRIBUTE)
.type(AnnotationElement.AttributeType.BOOLEAN)
.defaultValue(false)
.attribute(INDEX_NULL_AS_ATTRIBUTE)
.type(AnnotationElement.AttributeType.STRING)
.defaultValue(Values.DO_NOT_INDEX_NULL)
.annotation(KEYWORD_ANNOTATION, AnnotationElement.AnnotationTarget.FIELD)
.attribute(NAME_ATTRIBUTE)
.type(AnnotationElement.AttributeType.STRING)
.defaultValue("")
.attribute(SEARCHABLE_ATTRIBUTE)
.type(AnnotationElement.AttributeType.BOOLEAN)
.defaultValue(true)
.attribute(PROJECTABLE_ATTRIBUTE)
.type(AnnotationElement.AttributeType.BOOLEAN)
.defaultValue(false)
.attribute(AGGREGABLE_ATTRIBUTE)
.type(AnnotationElement.AttributeType.BOOLEAN)
.defaultValue(false)
.attribute(SORTABLE_ATTRIBUTE)
.type(AnnotationElement.AttributeType.BOOLEAN)
.defaultValue(false)
.attribute(INDEX_NULL_AS_ATTRIBUTE)
.type(AnnotationElement.AttributeType.STRING)
.defaultValue(Values.DO_NOT_INDEX_NULL)
.attribute(NORMALIZER_ATTRIBUTE)
.type(AnnotationElement.AttributeType.STRING)
.defaultValue("")
.attribute(NORMS_ATTRIBUTE)
.type(AnnotationElement.AttributeType.BOOLEAN)
.defaultValue(true)
.annotation(TEXT_ANNOTATION, AnnotationElement.AnnotationTarget.FIELD)
.attribute(NAME_ATTRIBUTE)
.type(AnnotationElement.AttributeType.STRING)
.defaultValue("")
.attribute(SEARCHABLE_ATTRIBUTE)
.type(AnnotationElement.AttributeType.BOOLEAN)
.defaultValue(true)
.attribute(PROJECTABLE_ATTRIBUTE)
.type(AnnotationElement.AttributeType.BOOLEAN)
.defaultValue(false)
.attribute(ANALYZER_ATTRIBUTE)
.type(AnnotationElement.AttributeType.STRING)
.defaultValue("standard")
.attribute(SEARCH_ANALYZER_ATTRIBUTE)
.type(AnnotationElement.AttributeType.STRING)
.defaultValue("")
.attribute(NORMS_ATTRIBUTE)
.type(AnnotationElement.AttributeType.BOOLEAN)
.defaultValue(true)
.attribute(TERM_VECTOR_ATTRIBUTE)
.type(AnnotationElement.AttributeType.IDENTIFIER)
.packageName(ANNOTATIONS_OPTIONS_PACKAGE)
.allowedValues(termVectorAllowedValues())
.defaultValue(TermVector.NO.name())
.annotation(DECIMAL_ANNOTATION, AnnotationElement.AnnotationTarget.FIELD)
.attribute(NAME_ATTRIBUTE)
.type(AnnotationElement.AttributeType.STRING)
.defaultValue("")
.attribute(SEARCHABLE_ATTRIBUTE)
.type(AnnotationElement.AttributeType.BOOLEAN)
.defaultValue(true)
.attribute(PROJECTABLE_ATTRIBUTE)
.type(AnnotationElement.AttributeType.BOOLEAN)
.defaultValue(false)
.attribute(AGGREGABLE_ATTRIBUTE)
.type(AnnotationElement.AttributeType.BOOLEAN)
.defaultValue(false)
.attribute(SORTABLE_ATTRIBUTE)
.type(AnnotationElement.AttributeType.BOOLEAN)
.defaultValue(false)
.attribute(INDEX_NULL_AS_ATTRIBUTE)
.type(AnnotationElement.AttributeType.STRING)
.defaultValue(Values.DO_NOT_INDEX_NULL)
.attribute(DECIMAL_SCALE_ATTRIBUTE)
.type(AnnotationElement.AttributeType.INT)
.defaultValue(2)
.annotation(EMBEDDED_ANNOTATION, AnnotationElement.AnnotationTarget.FIELD)
.attribute(NAME_ATTRIBUTE)
.type(AnnotationElement.AttributeType.STRING)
.defaultValue("")
.attribute(INCLUDE_DEPTH_ATTRIBUTE)
.type(AnnotationElement.AttributeType.INT)
.defaultValue(3)
.attribute(STRUCTURE_ATTRIBUTE)
.type(AnnotationElement.AttributeType.IDENTIFIER)
.packageName(ANNOTATIONS_OPTIONS_PACKAGE)
.allowedValues(structureAllowedValues())
.defaultValue(Structure.NESTED.name());
}
public static final TermVector termVector(String value) {
int beginIndex = value.lastIndexOf(".");
if (beginIndex >= 0) {
value = value.substring(beginIndex + 1);
}
return TermVector.valueOf(value);
}
public static final Structure structure(String value) {
int beginIndex = value.lastIndexOf(".");
if (beginIndex >= 0) {
value = value.substring(beginIndex + 1);
}
return Structure.valueOf(value);
}
private static final String[] termVectorAllowedValues() {
int capacity = TermVector.values().length * 2;
ArrayList<String> result = new ArrayList<>(capacity);
for (TermVector value : TermVector.values()) {
result.add(value.name());
result.add("TermVector." + value.name());
}
return result.toArray(new String[capacity]);
}
private static final String[] structureAllowedValues() {
int capacity = Structure.values().length * 2;
ArrayList<String> result = new ArrayList<>(capacity);
for (Structure value : Structure.values()) {
result.add(value.name());
result.add("Structure." + value.name());
}
return result.toArray(new String[capacity]);
}
}
| 8,592
| 46.214286
| 109
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/indexing/infinispan/InfinispanMetadataCreator.java
|
package org.infinispan.query.remote.impl.indexing.infinispan;
import java.util.Map;
import org.infinispan.api.annotations.indexing.model.Values;
import org.infinispan.api.annotations.indexing.option.Structure;
import org.infinispan.api.annotations.indexing.option.TermVector;
import org.infinispan.protostream.descriptors.AnnotationElement;
import org.infinispan.protostream.descriptors.FieldDescriptor;
import org.infinispan.query.remote.impl.indexing.FieldMapping;
public final class InfinispanMetadataCreator {
public static FieldMapping fieldMapping(FieldDescriptor fieldDescriptor, Map<String, AnnotationElement.Annotation> annotations) {
AnnotationElement.Annotation fieldAnnotation = annotations.get(InfinispanAnnotations.BASIC_ANNOTATION);
if (fieldAnnotation != null) {
return basic(fieldDescriptor, fieldAnnotation);
}
fieldAnnotation = annotations.get(InfinispanAnnotations.KEYWORD_ANNOTATION);
if (fieldAnnotation != null) {
return keyword(fieldDescriptor, fieldAnnotation);
}
fieldAnnotation = annotations.get(InfinispanAnnotations.TEXT_ANNOTATION);
if (fieldAnnotation != null) {
return text(fieldDescriptor, fieldAnnotation);
}
fieldAnnotation = annotations.get(InfinispanAnnotations.DECIMAL_ANNOTATION);
if (fieldAnnotation != null) {
return decimal(fieldDescriptor, fieldAnnotation);
}
fieldAnnotation = annotations.get(InfinispanAnnotations.EMBEDDED_ANNOTATION);
if (fieldAnnotation != null) {
return embedded(fieldDescriptor, fieldAnnotation);
}
return null;
}
private static FieldMapping basic(FieldDescriptor fieldDescriptor, AnnotationElement.Annotation fieldAnnotation) {
String name = name(fieldDescriptor, fieldAnnotation);
String indexNullAs = indexNullAs(fieldAnnotation);
Boolean searchable = (Boolean) fieldAnnotation.getAttributeValue(InfinispanAnnotations.SEARCHABLE_ATTRIBUTE).getValue();
Boolean projectable = (Boolean) fieldAnnotation.getAttributeValue(InfinispanAnnotations.PROJECTABLE_ATTRIBUTE).getValue();
Boolean aggregable = (Boolean) fieldAnnotation.getAttributeValue(InfinispanAnnotations.AGGREGABLE_ATTRIBUTE).getValue();
Boolean sortable = (Boolean) fieldAnnotation.getAttributeValue(InfinispanAnnotations.SORTABLE_ATTRIBUTE).getValue();
return new FieldMapping(name, searchable, projectable, aggregable, sortable,
null, null, indexNullAs, fieldDescriptor);
}
private static FieldMapping keyword(FieldDescriptor fieldDescriptor, AnnotationElement.Annotation fieldAnnotation) {
String name = name(fieldDescriptor, fieldAnnotation);
String indexNullAs = indexNullAs(fieldAnnotation);
Boolean searchable = (Boolean) fieldAnnotation.getAttributeValue(InfinispanAnnotations.SEARCHABLE_ATTRIBUTE).getValue();
Boolean projectable = (Boolean) fieldAnnotation.getAttributeValue(InfinispanAnnotations.PROJECTABLE_ATTRIBUTE).getValue();
Boolean aggregable = (Boolean) fieldAnnotation.getAttributeValue(InfinispanAnnotations.AGGREGABLE_ATTRIBUTE).getValue();
Boolean sortable = (Boolean) fieldAnnotation.getAttributeValue(InfinispanAnnotations.SORTABLE_ATTRIBUTE).getValue();
String normalizer = (String) fieldAnnotation.getAttributeValue(InfinispanAnnotations.NORMALIZER_ATTRIBUTE).getValue();
if ("".equals(normalizer)) {
normalizer = null;
}
Boolean norms = (Boolean) fieldAnnotation.getAttributeValue(InfinispanAnnotations.NORMS_ATTRIBUTE).getValue();
return new FieldMapping(name, searchable, projectable, aggregable, sortable,
null, normalizer, indexNullAs, norms, null, null, null, null, null, fieldDescriptor);
}
private static FieldMapping text(FieldDescriptor fieldDescriptor, AnnotationElement.Annotation fieldAnnotation) {
String name = name(fieldDescriptor, fieldAnnotation);
Boolean searchable = (Boolean) fieldAnnotation.getAttributeValue(InfinispanAnnotations.SEARCHABLE_ATTRIBUTE).getValue();
Boolean projectable = (Boolean) fieldAnnotation.getAttributeValue(InfinispanAnnotations.PROJECTABLE_ATTRIBUTE).getValue();
String analyzer = (String) fieldAnnotation.getAttributeValue(InfinispanAnnotations.ANALYZER_ATTRIBUTE).getValue();
String searchAnalyzer = (String) fieldAnnotation.getAttributeValue(InfinispanAnnotations.SEARCH_ANALYZER_ATTRIBUTE).getValue();
if ("".equals(searchAnalyzer)) {
searchAnalyzer = null;
}
Boolean norms = (Boolean) fieldAnnotation.getAttributeValue(InfinispanAnnotations.NORMS_ATTRIBUTE).getValue();
TermVector termVector = InfinispanAnnotations
.termVector((String) fieldAnnotation.getAttributeValue(InfinispanAnnotations.TERM_VECTOR_ATTRIBUTE).getValue());
return new FieldMapping(name, searchable, projectable, false, false,
analyzer, null, null, norms, searchAnalyzer, termVector, null, null, null, fieldDescriptor);
}
private static FieldMapping decimal(FieldDescriptor fieldDescriptor, AnnotationElement.Annotation fieldAnnotation) {
String name = name(fieldDescriptor, fieldAnnotation);
String indexNullAs = indexNullAs(fieldAnnotation);
Boolean searchable = (Boolean) fieldAnnotation.getAttributeValue(InfinispanAnnotations.SEARCHABLE_ATTRIBUTE).getValue();
Boolean projectable = (Boolean) fieldAnnotation.getAttributeValue(InfinispanAnnotations.PROJECTABLE_ATTRIBUTE).getValue();
Boolean aggregable = (Boolean) fieldAnnotation.getAttributeValue(InfinispanAnnotations.AGGREGABLE_ATTRIBUTE).getValue();
Boolean sortable = (Boolean) fieldAnnotation.getAttributeValue(InfinispanAnnotations.SORTABLE_ATTRIBUTE).getValue();
Integer decimalScale = (Integer) fieldAnnotation.getAttributeValue(InfinispanAnnotations.DECIMAL_SCALE_ATTRIBUTE).getValue();
return new FieldMapping(name, searchable, projectable, aggregable, sortable,
null, null, indexNullAs, null, null, null, decimalScale, null, null, fieldDescriptor);
}
private static FieldMapping embedded(FieldDescriptor fieldDescriptor, AnnotationElement.Annotation fieldAnnotation) {
String name = name(fieldDescriptor, fieldAnnotation);
Integer includeDepth = (Integer) fieldAnnotation.getAttributeValue(InfinispanAnnotations.INCLUDE_DEPTH_ATTRIBUTE).getValue();
Structure structure = InfinispanAnnotations
.structure((String) fieldAnnotation.getAttributeValue(InfinispanAnnotations.STRUCTURE_ATTRIBUTE).getValue());
return new FieldMapping(name, true, false, false, false,
null, null, null, null, null, null, null, includeDepth, structure, fieldDescriptor);
}
private static String name(FieldDescriptor fieldDescriptor, AnnotationElement.Annotation fieldAnnotation) {
String name = (String) fieldAnnotation.getAttributeValue(InfinispanAnnotations.NAME_ATTRIBUTE).getValue();
if (name == null) {
name = fieldDescriptor.getName();
}
return name;
}
private static String indexNullAs(AnnotationElement.Annotation fieldAnnotation) {
String indexNullAs = (String) fieldAnnotation.getAttributeValue(InfinispanAnnotations.INDEX_NULL_AS_ATTRIBUTE).getValue();
if (Values.DO_NOT_INDEX_NULL.equals(indexNullAs)) {
indexNullAs = null;
}
return indexNullAs;
}
}
| 7,409
| 52.695652
| 133
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/indexing/aggregator/BigIntegerAggregator.java
|
package org.infinispan.query.remote.impl.indexing.aggregator;
import java.math.BigInteger;
import org.hibernate.search.engine.backend.document.IndexFieldReference;
import org.infinispan.protostream.descriptors.FieldDescriptor;
import org.infinispan.protostream.descriptors.Type;
import org.infinispan.query.remote.impl.indexing.IndexingMessageContext;
public class BigIntegerAggregator implements TypeAggregator {
private final IndexFieldReference<?> fieldReference;
private byte[] bytes;
public BigIntegerAggregator(IndexFieldReference<?> fieldReference) {
this.fieldReference = fieldReference;
}
@Override
public void add(FieldDescriptor fieldDescriptor, Object tagValue) {
if (Type.BYTES.equals(fieldDescriptor.getType())) {
bytes = (byte[]) tagValue;
}
}
@Override
public void addValue(IndexingMessageContext document) {
if (bytes != null) {
document.addValue(fieldReference, new BigInteger(bytes));
}
}
}
| 996
| 28.323529
| 72
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/indexing/aggregator/BigDecimalAggregator.java
|
package org.infinispan.query.remote.impl.indexing.aggregator;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.hibernate.search.engine.backend.document.IndexFieldReference;
import org.infinispan.protostream.descriptors.FieldDescriptor;
import org.infinispan.protostream.descriptors.Type;
import org.infinispan.query.remote.impl.indexing.IndexingMessageContext;
public class BigDecimalAggregator implements TypeAggregator {
private final IndexFieldReference<?> fieldReference;
private byte[] unscaledValue;
private int scale;
public BigDecimalAggregator(IndexFieldReference<?> fieldReference) {
this.fieldReference = fieldReference;
}
@Override
public void add(FieldDescriptor fieldDescriptor, Object tagValue) {
if (Type.BYTES.equals(fieldDescriptor.getType())) {
unscaledValue = (byte[]) tagValue;
} else if (Type.INT32.equals(fieldDescriptor.getType())) {
scale = (int) tagValue;
}
}
@Override
public void addValue(IndexingMessageContext document) {
if (unscaledValue != null) {
document.addValue(fieldReference, new BigDecimal(new BigInteger(unscaledValue), scale));
}
}
}
| 1,201
| 29.820513
| 97
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/indexing/aggregator/TypeAggregator.java
|
package org.infinispan.query.remote.impl.indexing.aggregator;
import org.infinispan.protostream.descriptors.FieldDescriptor;
import org.infinispan.query.remote.impl.indexing.IndexingMessageContext;
public interface TypeAggregator {
void add(FieldDescriptor fieldDescriptor, Object tagValue);
void addValue(IndexingMessageContext document);
}
| 353
| 26.230769
| 72
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/logging/Log.java
|
package org.infinispan.query.remote.impl.logging;
import static org.jboss.logging.Logger.Level.WARN;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.commons.CacheException;
import org.jboss.logging.BasicLogger;
import org.jboss.logging.annotations.Cause;
import org.jboss.logging.annotations.LogMessage;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.MessageLogger;
import org.jboss.logging.annotations.ValidIdRange;
/**
* Log abstraction for the remote query module. For this module, message ids ranging from 28001 to 28500 inclusively
* have been reserved.
*
* @author anistor@redhat.com
* @since 6.0
*/
@MessageLogger(projectCode = "ISPN")
@ValidIdRange(min = 28001, max = 28500)
public interface Log extends BasicLogger {
/*@Message(value = "Unknown field %s in type %s", id = 28001)
IllegalArgumentException unknownField(String fieldName, String fullyQualifiedTypeName);
@Message(value = "Field %s from type %s is not indexed", id = 28002)
IllegalArgumentException fieldIsNotIndexed(String fieldName, String fullyQualifiedTypeName);
@Message(value = "An exception has occurred during query execution", id = 28003)
CacheException errorExecutingQuery(@Cause Throwable cause);*/
@Message(value = "Querying is not enabled on cache %s", id = 28004)
CacheException queryingNotEnabled(String cacheName);
/*@Message(value = "Field %s from type %s is not analyzed", id = 28005)
IllegalArgumentException fieldIsNotAnalyzed(String fieldName, String fullyQualifiedTypeName);
@Message(value = "An exception has occurred during filter execution", id = 28006)
CacheException errorFiltering(@Cause Throwable cause);*/
@Message(value = "The key must be a String : %s", id = 28007)
CacheException keyMustBeString(Class<?> c);
@Message(value = "The value must be a String : %s", id = 28008)
CacheException valueMustBeString(Class<?> c);
@Message(value = "The key must be a String ending with \".proto\" : %s", id = 28009)
CacheException keyMustBeStringEndingWithProto(Object key);
@Message(value = "Failed to parse proto file.", id = 28010)
CacheException failedToParseProtoFile(@Cause Throwable cause);
@Message(value = "Failed to parse proto file : %s", id = 28011)
CacheException failedToParseProtoFile(String fileName, @Cause Throwable cause);
@Message(value = "Error during execution of protostream serialization context initializer", id = 28013)
CacheException errorInitializingSerCtx(@Cause Throwable cause);
@Message(value = "The '%s' cache does not support commands of type %s", id = 28014)
CacheException cacheDoesNotSupportCommand(String cacheName, String commandType);
@Message(value = "Cache '%s' with storage type '%s' cannot be queried. Please configure the cache encoding as " +
"'application/x-protostream' or 'application/x-java-object'", id = 28015)
CacheException cacheNotQueryable(String cacheName, String storage);
@LogMessage(level = WARN)
@Message(id = 28016, value = "Query performed in a cache ('%s') that has an unknown format configuration. " +
"Please configure the cache encoding as 'application/x-protostream' or 'application/x-java-object'")
void warnNoMediaType(String cacheName);
/*@Message(id = 28017, value = "Type '%s' was not declared as an indexed entity. " +
"Please declare it in the indexing configuration of your cache and ensure the type is defined by a schema before this cache is started.")
CacheConfigurationException indexingUndeclaredType(String typeName);*/
@Message(id = 28018, value = "It is not possible to create indexes for a field having type %s. Field: %s.")
CacheException fieldTypeNotIndexable(String typeName, String fieldName);
/*@LogMessage(level = INFO)
@Message(id = 28019, value = "Registering protostream serialization context initializer: %s")
void registeringSerializationContextInitializer(String className);*/
/*@Message(id = 28020, value = "It is not possible to create indexes for a field having type %s. Field: %s.")
CacheException typeNotIndexable(String typeName, String fieldName);*/
@Message(id = 28021, value = "The configured indexed-entity type '%s' must be indexed. Please annotate it with @Indexed and make sure at least one field has the @Field annotation, or remove it from the configuration.")
CacheConfigurationException typeNotIndexed(String typeName);
@Message(id = 28022, value = "The declared indexed type '%s' is not known. Please register its proto schema file first")
CacheConfigurationException unknownType(String typeName);
}
| 4,666
| 48.648936
| 221
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/filter/IckleContinuousQueryProtobufCacheEventFilterConverterFactory.java
|
package org.infinispan.query.remote.impl.filter;
import java.util.Map;
import org.infinispan.filter.NamedFactory;
import org.infinispan.notifications.cachelistener.filter.CacheEventFilterConverter;
import org.infinispan.notifications.cachelistener.filter.CacheEventFilterConverterFactory;
import org.infinispan.objectfilter.impl.ProtobufMatcher;
import org.kohsuke.MetaInfServices;
/**
* @author anistor@redhat.com
* @since 8.0
*/
@NamedFactory(name = IckleContinuousQueryProtobufCacheEventFilterConverterFactory.FACTORY_NAME)
@MetaInfServices(CacheEventFilterConverterFactory.class)
public final class IckleContinuousQueryProtobufCacheEventFilterConverterFactory
extends AbstractIckleFilterConverterFactory<CacheEventFilterConverter>
implements CacheEventFilterConverterFactory {
public static final String FACTORY_NAME = "continuous-query-filter-converter-factory";
@Override
protected CacheEventFilterConverter getFilterConverter(String queryString, Map<String, Object> namedParams) {
return new IckleContinuousQueryProtobufCacheEventFilterConverter(queryString, namedParams, ProtobufMatcher.class);
}
}
| 1,145
| 39.928571
| 120
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/filter/IckleProtobufFilterAndConverter.java
|
package org.infinispan.query.remote.impl.filter;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.io.UnsignedNumeric;
import org.infinispan.commons.marshall.AbstractExternalizer;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.objectfilter.impl.ProtobufMatcher;
import org.infinispan.query.core.impl.QueryCache;
import org.infinispan.query.core.impl.eventfilter.IckleFilterAndConverter;
import org.infinispan.query.remote.impl.ExternalizerIds;
import org.infinispan.query.remote.impl.RemoteQueryManager;
/**
* A subclass of {@link IckleFilterAndConverter} that is able to deal with binary protobuf values wrapped in a
* ProtobufValueWrapper.
*
* @author anistor@redhat.com
* @since 7.2
*/
public final class IckleProtobufFilterAndConverter extends IckleFilterAndConverter<Object, Object> {
public IckleProtobufFilterAndConverter(String queryString, Map<String, Object> namedParameters) {
super(queryString, namedParameters, ProtobufMatcher.class);
}
@Override
protected void injectDependencies(ComponentRegistry componentRegistry, QueryCache queryCache) {
RemoteQueryManager remoteQueryManager = componentRegistry.getComponent(RemoteQueryManager.class);
matcherImplClass = remoteQueryManager.getMatcherClass(MediaType.APPLICATION_PROTOSTREAM);
super.injectDependencies(componentRegistry, queryCache);
}
public static final class Externalizer extends AbstractExternalizer<IckleProtobufFilterAndConverter> {
@Override
public void writeObject(ObjectOutput output, IckleProtobufFilterAndConverter filterAndConverter) throws IOException {
output.writeUTF(filterAndConverter.getQueryString());
Map<String, Object> namedParameters = filterAndConverter.getNamedParameters();
if (namedParameters != null) {
UnsignedNumeric.writeUnsignedInt(output, namedParameters.size());
for (Map.Entry<String, Object> e : namedParameters.entrySet()) {
output.writeUTF(e.getKey());
output.writeObject(e.getValue());
}
} else {
UnsignedNumeric.writeUnsignedInt(output, 0);
}
}
@Override
public IckleProtobufFilterAndConverter readObject(ObjectInput input) throws IOException, ClassNotFoundException {
String queryString = input.readUTF();
int paramsSize = UnsignedNumeric.readUnsignedInt(input);
Map<String, Object> namedParameters = null;
if (paramsSize != 0) {
namedParameters = new HashMap<>(paramsSize);
for (int i = 0; i < paramsSize; i++) {
String paramName = input.readUTF();
Object paramValue = input.readObject();
namedParameters.put(paramName, paramValue);
}
}
return new IckleProtobufFilterAndConverter(queryString, namedParameters);
}
@Override
public Integer getId() {
return ExternalizerIds.ICKLE_PROTOBUF_FILTER_AND_CONVERTER;
}
@Override
public Set<Class<? extends IckleProtobufFilterAndConverter>> getTypeClasses() {
return Collections.singleton(IckleProtobufFilterAndConverter.class);
}
}
}
| 3,440
| 39.482353
| 123
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/filter/IckleContinuousQueryProtobufCacheEventFilterConverter.java
|
package org.infinispan.query.remote.impl.filter;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_PROTOSTREAM;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.infinispan.Cache;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.io.UnsignedNumeric;
import org.infinispan.commons.marshall.AbstractExternalizer;
import org.infinispan.metadata.Metadata;
import org.infinispan.notifications.cachelistener.filter.EventType;
import org.infinispan.objectfilter.Matcher;
import org.infinispan.objectfilter.ObjectFilter;
import org.infinispan.query.core.impl.continuous.IckleContinuousQueryCacheEventFilterConverter;
import org.infinispan.query.remote.client.impl.ContinuousQueryResult;
import org.infinispan.query.remote.impl.ExternalizerIds;
import org.infinispan.query.remote.impl.RemoteQueryManager;
/**
* @author anistor@redhat.com
* @since 8.0
*/
public final class IckleContinuousQueryProtobufCacheEventFilterConverter extends IckleContinuousQueryCacheEventFilterConverter<Object, Object, Object> {
private RemoteQueryManager remoteQueryManager;
IckleContinuousQueryProtobufCacheEventFilterConverter(String queryString, Map<String, Object> namedParameters, Class<? extends Matcher> matcherImplClass) {
super(queryString, namedParameters, matcherImplClass);
}
@Override
protected void injectDependencies(Cache<?, ?> cache) {
remoteQueryManager = cache.getAdvancedCache().getComponentRegistry().getComponent(RemoteQueryManager.class);
matcherImplClass = remoteQueryManager.getMatcherClass(APPLICATION_PROTOSTREAM);
super.injectDependencies(cache);
}
@Override
public Object filterAndConvert(Object key, Object oldValue, Metadata oldMetadata, Object newValue, Metadata newMetadata, EventType eventType) {
if (eventType.isExpired()) {
oldValue = newValue; // expired events have the expired value as newValue
newValue = null;
}
ObjectFilter objectFilter = getObjectFilter();
ObjectFilter.FilterResult f1 = oldValue == null ? null : objectFilter.filter(key, oldValue);
ObjectFilter.FilterResult f2 = newValue == null ? null : objectFilter.filter(key, newValue);
if (f1 == null && f2 != null) {
// result joining
return makeFilterResult(ContinuousQueryResult.ResultType.JOINING, key, f2.getProjection() == null ? newValue : null, f2.getProjection());
} else if (f1 != null && f2 == null) {
// result leaving
return makeFilterResult(ContinuousQueryResult.ResultType.LEAVING, key, null, null);
} else {
return null;
}
}
private Object makeFilterResult(ContinuousQueryResult.ResultType resultType, Object key, Object value, Object[] projection) {
key = remoteQueryManager.convertKey(key, MediaType.APPLICATION_PROTOSTREAM);
if (value != null) {
value = remoteQueryManager.convertValue(value, MediaType.APPLICATION_PROTOSTREAM);
}
ContinuousQueryResult result = new ContinuousQueryResult(resultType, (byte[]) key, (byte[]) value, projection);
return remoteQueryManager.encodeFilterResult(result);
}
@Override
public String toString() {
return "IckleContinuousQueryProtobufCacheEventFilterConverter{queryString='" + queryString + "'}";
}
public static final class Externalizer extends AbstractExternalizer<IckleContinuousQueryProtobufCacheEventFilterConverter> {
@Override
public void writeObject(ObjectOutput output, IckleContinuousQueryProtobufCacheEventFilterConverter filterAndConverter) throws IOException {
output.writeUTF(filterAndConverter.queryString);
Map<String, Object> namedParameters = filterAndConverter.namedParameters;
if (namedParameters != null) {
UnsignedNumeric.writeUnsignedInt(output, namedParameters.size());
for (Map.Entry<String, Object> e : namedParameters.entrySet()) {
output.writeUTF(e.getKey());
output.writeObject(e.getValue());
}
} else {
UnsignedNumeric.writeUnsignedInt(output, 0);
}
output.writeObject(filterAndConverter.matcherImplClass);
}
@Override
@SuppressWarnings("unchecked")
public IckleContinuousQueryProtobufCacheEventFilterConverter readObject(ObjectInput input) throws IOException, ClassNotFoundException {
String queryString = input.readUTF();
int paramsSize = UnsignedNumeric.readUnsignedInt(input);
Map<String, Object> namedParameters = null;
if (paramsSize != 0) {
namedParameters = new HashMap<>(paramsSize);
for (int i = 0; i < paramsSize; i++) {
String paramName = input.readUTF();
Object paramValue = input.readObject();
namedParameters.put(paramName, paramValue);
}
}
Class<? extends Matcher> matcherImplClass = (Class<? extends Matcher>) input.readObject();
return new IckleContinuousQueryProtobufCacheEventFilterConverter(queryString, namedParameters, matcherImplClass);
}
@Override
public Integer getId() {
return ExternalizerIds.ICKLE_CONTINUOUS_QUERY_CACHE_EVENT_FILTER_CONVERTER;
}
@Override
public Set<Class<? extends IckleContinuousQueryProtobufCacheEventFilterConverter>> getTypeClasses() {
return Collections.singleton(IckleContinuousQueryProtobufCacheEventFilterConverter.class);
}
}
}
| 5,675
| 43.692913
| 158
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/filter/SecurityActions.java
|
package org.infinispan.query.remote.impl.filter;
import static org.infinispan.security.Security.doPrivileged;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.protostream.SerializationContext;
import org.infinispan.query.remote.impl.GetSerializationContextAction;
/**
* SecurityActions for the org.infinispan.query.remote.impl.filter package.
*
* Do not move and do not change class and method visibility!
*
* @author Dan Berindei
* @since 10.0
*/
final class SecurityActions {
static SerializationContext getSerializationContext(EmbeddedCacheManager cacheManager) {
return doPrivileged(new GetSerializationContextAction(cacheManager));
}
}
| 689
| 29
| 91
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/filter/IckleBinaryProtobufFilterAndConverter.java
|
package org.infinispan.query.remote.impl.filter;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.marshall.AbstractExternalizer;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.filter.AbstractKeyValueFilterConverter;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.metadata.Metadata;
import org.infinispan.objectfilter.ObjectFilter;
import org.infinispan.protostream.ProtobufUtil;
import org.infinispan.protostream.SerializationContext;
import org.infinispan.query.remote.impl.ExternalizerIds;
/**
* Adapter for {@link IckleProtobufFilterAndConverter} that produces binary values as a result of filter/conversion.
*
* @author gustavonalle
* @since 8.1
*/
@Scope(Scopes.NONE)
public final class IckleBinaryProtobufFilterAndConverter<K, V> extends AbstractKeyValueFilterConverter<K, V, Object> {
private SerializationContext serCtx;
private final IckleProtobufFilterAndConverter delegate;
@Inject
void injectDependencies(ComponentRegistry componentRegistry, EmbeddedCacheManager cacheManager) {
componentRegistry.wireDependencies(delegate);
serCtx = SecurityActions.getSerializationContext(cacheManager);
}
IckleBinaryProtobufFilterAndConverter(String queryString, Map<String, Object> namedParameters) {
this.delegate = new IckleProtobufFilterAndConverter(queryString, namedParameters);
}
private IckleBinaryProtobufFilterAndConverter(IckleProtobufFilterAndConverter delegate) {
this.delegate = delegate;
}
@Override
public Object filterAndConvert(K key, V value, Metadata metadata) {
Optional<ObjectFilter.FilterResult> filterResult = Optional.ofNullable(delegate.filterAndConvert(key, value, metadata));
return filterResult.map(fr -> {
Object instance = fr.getInstance();
if (instance != null)
return instance;
return Arrays.stream(fr.getProjection()).map(this::toByteArray).toArray();
}).orElse(null);
}
private Object toByteArray(Object ref) {
try {
return ProtobufUtil.toWrappedByteArray(serCtx, ref);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public MediaType format() {
return MediaType.APPLICATION_PROTOSTREAM;
}
public static final class Externalizer extends AbstractExternalizer<IckleBinaryProtobufFilterAndConverter> {
@Override
public void writeObject(ObjectOutput output, IckleBinaryProtobufFilterAndConverter object) throws IOException {
output.writeObject(object.delegate);
}
@Override
public IckleBinaryProtobufFilterAndConverter readObject(ObjectInput input) throws IOException, ClassNotFoundException {
IckleProtobufFilterAndConverter delegate = (IckleProtobufFilterAndConverter) input.readObject();
return new IckleBinaryProtobufFilterAndConverter(delegate);
}
@Override
public Integer getId() {
return ExternalizerIds.ICKLE_BINARY_PROTOBUF_FILTER_AND_CONVERTER;
}
@Override
public Set<Class<? extends IckleBinaryProtobufFilterAndConverter>> getTypeClasses() {
return Collections.singleton(IckleBinaryProtobufFilterAndConverter.class);
}
}
}
| 3,651
| 34.803922
| 126
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/filter/IckleProtobufCacheEventFilterConverter.java
|
package org.infinispan.query.remote.impl.filter;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collections;
import java.util.Set;
import org.infinispan.Cache;
import org.infinispan.commons.marshall.AbstractExternalizer;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.metadata.Metadata;
import org.infinispan.notifications.cachelistener.filter.EventType;
import org.infinispan.objectfilter.ObjectFilter;
import org.infinispan.query.core.impl.eventfilter.IckleCacheEventFilterConverter;
import org.infinispan.query.core.impl.eventfilter.IckleFilterAndConverter;
import org.infinispan.query.remote.client.FilterResult;
import org.infinispan.query.remote.impl.ExternalizerIds;
import org.infinispan.query.remote.impl.RemoteQueryManager;
/**
* @author anistor@redhat.com
* @since 7.2
*/
public final class IckleProtobufCacheEventFilterConverter extends IckleCacheEventFilterConverter<Object, Object, Object> {
private RemoteQueryManager remoteQueryManager;
IckleProtobufCacheEventFilterConverter(IckleFilterAndConverter<Object, Object> filterAndConverter) {
super(filterAndConverter);
}
@Inject
void injectDependencies(Cache cache) {
remoteQueryManager = cache.getAdvancedCache().getComponentRegistry().getComponent(RemoteQueryManager.class);
}
@Override
public Object filterAndConvert(Object key, Object oldValue, Metadata oldMetadata, Object newValue, Metadata newMetadata, EventType eventType) {
ObjectFilter.FilterResult filterResult = filterAndConverter.filterAndConvert(key, newValue, newMetadata);
if (filterResult != null) {
FilterResult result = new FilterResult(filterResult.getInstance(), filterResult.getProjection(), filterResult.getSortProjection());
return remoteQueryManager.encodeFilterResult(result);
}
return null;
}
public static final class Externalizer extends AbstractExternalizer<IckleProtobufCacheEventFilterConverter> {
@Override
public void writeObject(ObjectOutput output, IckleProtobufCacheEventFilterConverter object) throws IOException {
output.writeObject(object.filterAndConverter);
}
@Override
public IckleProtobufCacheEventFilterConverter readObject(ObjectInput input) throws IOException, ClassNotFoundException {
IckleFilterAndConverter<Object, Object> filterAndConverter = (IckleFilterAndConverter<Object, Object>) input.readObject();
return new IckleProtobufCacheEventFilterConverter(filterAndConverter);
}
@Override
public Integer getId() {
return ExternalizerIds.ICKLE_PROTOBUF_CACHE_EVENT_FILTER_CONVERTER;
}
@Override
public Set<Class<? extends IckleProtobufCacheEventFilterConverter>> getTypeClasses() {
return Collections.singleton(IckleProtobufCacheEventFilterConverter.class);
}
}
}
| 2,926
| 39.652778
| 146
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/filter/IckleCacheEventFilterConverterFactory.java
|
package org.infinispan.query.remote.impl.filter;
import java.util.Map;
import org.infinispan.filter.NamedFactory;
import org.infinispan.notifications.cachelistener.filter.CacheEventFilterConverter;
import org.infinispan.notifications.cachelistener.filter.CacheEventFilterConverterFactory;
import org.kohsuke.MetaInfServices;
/**
* @author anistor@redhat.com
* @since 7.2
*/
@NamedFactory(name = IckleCacheEventFilterConverterFactory.FACTORY_NAME)
@MetaInfServices(CacheEventFilterConverterFactory.class)
public final class IckleCacheEventFilterConverterFactory
extends AbstractIckleFilterConverterFactory<CacheEventFilterConverter>
implements CacheEventFilterConverterFactory {
public static final String FACTORY_NAME = "query-dsl-filter-converter-factory";
@Override
protected CacheEventFilterConverter getFilterConverter(String queryString, Map<String, Object> namedParams) {
return new IckleProtobufCacheEventFilterConverter(new IckleProtobufFilterAndConverter(queryString, namedParams));
}
}
| 1,034
| 37.333333
| 119
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/filter/ContinuousQueryResultExternalizer.java
|
package org.infinispan.query.remote.impl.filter;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collections;
import java.util.Set;
import org.infinispan.commons.marshall.AbstractExternalizer;
import org.infinispan.query.remote.client.impl.ContinuousQueryResult;
import org.infinispan.query.remote.impl.ExternalizerIds;
/**
* A 'remote' ContinuousQueryResult needs jboss-marshalling serializability between nodes when running with object storage.
* It will only be marshalled using protobuf before passing it to the remote client.
*
* @author anistor@redhat.com
* @since 9.0
*/
public final class ContinuousQueryResultExternalizer extends AbstractExternalizer<ContinuousQueryResult> {
@Override
public void writeObject(ObjectOutput output, ContinuousQueryResult continuousQueryResult) throws IOException {
output.writeInt(continuousQueryResult.getResultType().ordinal());
output.writeInt(continuousQueryResult.getKey().length);
output.write(continuousQueryResult.getKey());
if (continuousQueryResult.getResultType() != ContinuousQueryResult.ResultType.LEAVING) {
Object[] projection = continuousQueryResult.getProjection();
if (projection == null) {
output.writeInt(continuousQueryResult.getValue().length);
output.write(continuousQueryResult.getValue());
} else {
// skip serializing the instance if there is a projection
output.writeInt(-1);
int projLen = projection.length;
output.writeInt(projLen);
for (Object prj : projection) {
output.writeObject(prj);
}
}
}
}
@Override
public ContinuousQueryResult readObject(ObjectInput input) throws IOException, ClassNotFoundException {
ContinuousQueryResult.ResultType resultType = ContinuousQueryResult.ResultType.values()[input.readInt()];
int keyLen = input.readInt();
byte[] key = new byte[keyLen];
input.readFully(key);
byte[] value = null;
Object[] projection = null;
if (resultType != ContinuousQueryResult.ResultType.LEAVING) {
int valueLen = input.readInt();
if (valueLen == -1) {
int projLen = input.readInt();
projection = new Object[projLen];
for (int i = 0; i < projLen; i++) {
projection[i] = input.readObject();
}
} else {
value = new byte[valueLen];
input.readFully(value);
}
}
return new ContinuousQueryResult(resultType, key, value, projection);
}
@Override
public Integer getId() {
return ExternalizerIds.ICKLE_CONTINUOUS_QUERY_RESULT;
}
@Override
public Set<Class<? extends ContinuousQueryResult>> getTypeClasses() {
return Collections.singleton(ContinuousQueryResult.class);
}
}
| 2,915
| 36.384615
| 123
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/filter/AbstractIckleFilterConverterFactory.java
|
package org.infinispan.query.remote.impl.filter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.marshall.ProtoStreamMarshaller;
/**
* @author gustavonalle
*/
abstract class AbstractIckleFilterConverterFactory<T> {
// This marshaller is able to handle primitive/scalar types only
private static final ProtoStreamMarshaller paramMarshaller = new ProtoStreamMarshaller();
private String unmarshallQueryString(Object[] params) {
try {
return (String) paramMarshaller.objectFromByteBuffer((byte[]) params[0]);
} catch (IOException | ClassNotFoundException e) {
throw new CacheException(e);
}
}
private Map<String, Object> unmarshallParams(Object[] params) {
Map<String, Object> namedParams = null;
try {
if (params.length > 1) {
namedParams = new HashMap<>((params.length - 1) / 2);
int i = 1;
while (i < params.length) {
String name = (String) paramMarshaller.objectFromByteBuffer((byte[]) params[i++]);
Object value = paramMarshaller.objectFromByteBuffer((byte[]) params[i++]);
namedParams.put(name, value);
}
}
} catch (IOException | ClassNotFoundException e) {
throw new CacheException(e);
}
return namedParams;
}
public final T getFilterConverter(Object[] params) {
String queryString = unmarshallQueryString(params);
Map<String, Object> namedParams = unmarshallParams(params);
return getFilterConverter(queryString, namedParams);
}
protected abstract T getFilterConverter(String queryString, Map<String, Object> namedParams);
}
| 1,775
| 33.153846
| 97
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/filter/IckleProtobufFilterAndConverterFactory.java
|
package org.infinispan.query.remote.impl.filter;
import java.util.Map;
import org.infinispan.filter.KeyValueFilterConverter;
import org.infinispan.filter.NamedFactory;
import org.infinispan.filter.ParamKeyValueFilterConverterFactory;
import org.kohsuke.MetaInfServices;
/**
* Factory for a {@link KeyValueFilterConverter} that operates on binary parameters and produces binary results.
*
* @author gustavonalle
* @since 8.1
*/
@NamedFactory(name = IckleProtobufFilterAndConverterFactory.FACTORY_NAME)
@MetaInfServices(ParamKeyValueFilterConverterFactory.class)
@SuppressWarnings("unused")
public final class IckleProtobufFilterAndConverterFactory
extends AbstractIckleFilterConverterFactory<KeyValueFilterConverter>
implements ParamKeyValueFilterConverterFactory {
public static final String FACTORY_NAME = "iteration-filter-converter-factory";
@Override
protected KeyValueFilterConverter getFilterConverter(String queryString, Map<String, Object> namedParams) {
return new IckleBinaryProtobufFilterAndConverter<>(queryString, namedParams);
}
@Override
public boolean binaryParam() {
return true;
}
}
| 1,158
| 31.194444
| 112
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/filter/FilterResultExternalizer.java
|
package org.infinispan.query.remote.impl.filter;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collections;
import java.util.Set;
import org.infinispan.commons.marshall.AbstractExternalizer;
import org.infinispan.query.remote.client.FilterResult;
import org.infinispan.query.remote.impl.ExternalizerIds;
/**
* A 'remote' FilterResult needs jboss-marshalling serializability between nodes when running with object storage.
* It will only be marshalled using protobuf before passing it to the remote client.
*
* @author anistor@redhat.com
* @since 9.0
*/
public final class FilterResultExternalizer extends AbstractExternalizer<FilterResult> {
@Override
public void writeObject(ObjectOutput output, FilterResult filterResult) throws IOException {
Object[] projection = filterResult.getProjection();
if (projection == null) {
// skip marshalling the instance if there is a projection
output.writeInt(-1);
output.writeObject(filterResult.getInstance());
} else {
output.writeInt(projection.length);
for (Object prj : projection) {
output.writeObject(prj);
}
}
Comparable[] sortProjection = filterResult.getSortProjection();
if (sortProjection == null) {
output.writeInt(-1);
} else {
output.writeInt(sortProjection.length);
for (Object prj : sortProjection) {
output.writeObject(prj);
}
}
}
@Override
public FilterResult readObject(ObjectInput input) throws IOException, ClassNotFoundException {
Object instance;
Object[] projection;
Comparable[] sortProjection;
int projLen = input.readInt();
if (projLen == -1) {
instance = input.readObject();
projection = null;
} else {
instance = null;
projection = new Object[projLen];
for (int i = 0; i < projLen; i++) {
projection[i] = input.readObject();
}
}
int sortProjLen = input.readInt();
if (sortProjLen == -1) {
sortProjection = null;
} else {
sortProjection = new Comparable[sortProjLen];
for (int i = 0; i < sortProjLen; i++) {
sortProjection[i] = (Comparable) input.readObject();
}
}
return new FilterResult(instance, projection, sortProjection);
}
@Override
public Integer getId() {
return ExternalizerIds.ICKLE_FILTER_RESULT;
}
@Override
public Set<Class<? extends FilterResult>> getTypeClasses() {
return Collections.singleton(FilterResult.class);
}
}
| 2,672
| 29.375
| 114
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/filter/IckleContinuousQueryProtobufFilterIndexingServiceProvider.java
|
package org.infinispan.query.remote.impl.filter;
import org.infinispan.Cache;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.notifications.cachelistener.filter.FilterIndexingServiceProvider;
import org.infinispan.notifications.cachelistener.filter.IndexedFilter;
import org.infinispan.query.core.impl.continuous.IckleContinuousQueryFilterIndexingServiceProvider;
import org.infinispan.query.remote.client.impl.ContinuousQueryResult;
import org.infinispan.query.remote.impl.RemoteQueryManager;
import org.kohsuke.MetaInfServices;
/**
* @author anistor@redhat.com
* @since 8.1
*/
@MetaInfServices(FilterIndexingServiceProvider.class)
public final class IckleContinuousQueryProtobufFilterIndexingServiceProvider extends IckleContinuousQueryFilterIndexingServiceProvider {
private RemoteQueryManager remoteQueryManager;
@Inject Cache cache;
public IckleContinuousQueryProtobufFilterIndexingServiceProvider() {
super(ContinuousQueryResult.ResultType.JOINING, ContinuousQueryResult.ResultType.UPDATED, ContinuousQueryResult.ResultType.LEAVING);
}
private RemoteQueryManager getRemoteQueryManager() {
if (remoteQueryManager == null) {
remoteQueryManager = cache.getAdvancedCache().getComponentRegistry().getComponent(RemoteQueryManager.class);
}
return remoteQueryManager;
}
@Override
public boolean supportsFilter(IndexedFilter<?, ?, ?> indexedFilter) {
return indexedFilter.getClass() == IckleContinuousQueryProtobufCacheEventFilterConverter.class;
}
@Override
protected Object makeFilterResult(Object userContext, Object eventType, Object key, Object instance, Object[] projection, Comparable[] sortProjection) {
key = getRemoteQueryManager().convertKey(key, MediaType.APPLICATION_PROTOSTREAM);
if (instance != null) {
instance = getRemoteQueryManager().convertValue(instance, MediaType.APPLICATION_PROTOSTREAM);
}
ContinuousQueryResult result = new ContinuousQueryResult((ContinuousQueryResult.ResultType) eventType, (byte[]) key, (byte[]) instance, projection);
return getRemoteQueryManager().encodeFilterResult(result);
}
}
| 2,234
| 41.169811
| 155
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/filter/IckleProtobufFilterIndexingServiceProvider.java
|
package org.infinispan.query.remote.impl.filter;
import org.infinispan.Cache;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.notifications.cachelistener.filter.FilterIndexingServiceProvider;
import org.infinispan.notifications.cachelistener.filter.IndexedFilter;
import org.infinispan.query.core.impl.eventfilter.IckleFilterIndexingServiceProvider;
import org.infinispan.query.remote.client.FilterResult;
import org.infinispan.query.remote.impl.RemoteQueryManager;
import org.kohsuke.MetaInfServices;
/**
* @author anistor@redhat.com
* @since 7.2
*/
@MetaInfServices(FilterIndexingServiceProvider.class)
public final class IckleProtobufFilterIndexingServiceProvider extends IckleFilterIndexingServiceProvider {
private RemoteQueryManager remoteQueryManager;
@Inject Cache cache;
private RemoteQueryManager getRemoteQueryManager() {
if (remoteQueryManager == null) {
remoteQueryManager = cache.getAdvancedCache().getComponentRegistry().getComponent(RemoteQueryManager.class);
}
return remoteQueryManager;
}
@Override
public boolean supportsFilter(IndexedFilter<?, ?, ?> indexedFilter) {
return indexedFilter.getClass() == IckleProtobufCacheEventFilterConverter.class;
}
@Override
protected Object makeFilterResult(Object userContext, Object eventType, Object key, Object instance, Object[] projection, Comparable[] sortProjection) {
Object filterResult = new FilterResult(instance, projection, sortProjection);
return getRemoteQueryManager().encodeFilterResult(filterResult);
}
}
| 1,591
| 37.829268
| 155
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/util/LazyRef.java
|
package org.infinispan.query.remote.impl.util;
import java.util.function.Supplier;
/**
* @since 9.2
*/
public class LazyRef<R> implements Supplier<R> {
private final Supplier<R> supplier;
private R supplied;
private volatile boolean available;
public LazyRef(Supplier<R> supplier) {
this.supplier = supplier;
}
@Override
public R get() {
if (!available) {
synchronized (this) {
if (!available) {
supplied = supplier.get();
available = true;
}
}
}
return supplied;
}
public boolean available() {
return available;
}
}
| 657
| 17.8
| 48
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/persistence/PersistenceContextInitializer.java
|
package org.infinispan.query.remote.impl.persistence;
import org.infinispan.marshall.persistence.impl.PersistenceMarshallerImpl;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder;
import org.infinispan.query.remote.impl.indexing.ProtobufValueWrapper;
/**
* Interface used to initialise the {@link PersistenceMarshallerImpl}'s {@link org.infinispan.protostream.SerializationContext}
* using the specified Pojos, Marshaller implementations and provided .proto schemas.
*
* @author Ryan Emerson
* @since 10.0
*/
@AutoProtoSchemaBuilder(
includeClasses = ProtobufValueWrapper.class,
schemaFileName = "persistence.remote_query.proto",
schemaFilePath = "proto/generated",
schemaPackageName = "org.infinispan.persistence.remote_query",
service = false
)
interface PersistenceContextInitializer extends SerializationContextInitializer {
}
| 955
| 38.833333
| 127
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/mapping/SerializationContextSearchMapping.java
|
package org.infinispan.query.remote.impl.mapping;
import java.util.Set;
import org.hibernate.search.mapper.pojo.loading.spi.PojoSelectionEntityLoader;
import org.hibernate.search.mapper.pojo.mapping.definition.programmatic.ProgrammaticMappingConfigurationContext;
import org.infinispan.protostream.SerializationContext;
import org.infinispan.query.remote.impl.indexing.ProtobufEntityConverter;
import org.infinispan.query.remote.impl.mapping.model.ProtobufBootstrapIntrospector;
import org.infinispan.query.remote.impl.mapping.reference.GlobalReferenceHolder;
import org.infinispan.query.remote.impl.mapping.typebridge.ProtobufMessageBinder;
import org.infinispan.search.mapper.mapping.SearchMappingBuilder;
import org.infinispan.search.mapper.mapping.SearchMappingCommonBuilding;
public final class SerializationContextSearchMapping {
private SerializationContextSearchMapping() {
}
public static SearchMappingBuilder createBuilder(SearchMappingCommonBuilding commonBuilding,
PojoSelectionEntityLoader<?> entityLoader,
Set<String> indexedEntityTypes,
SerializationContext serializationContext) {
GlobalReferenceHolder globalReferenceHolder = new GlobalReferenceHolder(serializationContext.getGenericDescriptors());
ProtobufBootstrapIntrospector introspector = new ProtobufBootstrapIntrospector();
SearchMappingBuilder builder = commonBuilding.builder(introspector);
builder.setEntityLoader(entityLoader);
builder.setEntityConverter(new ProtobufEntityConverter(serializationContext, globalReferenceHolder.getRootMessages()));
ProgrammaticMappingConfigurationContext programmaticMapping = builder.programmaticMapping();
boolean existIndexedEntities = false;
for (GlobalReferenceHolder.RootMessageInfo rootMessage : globalReferenceHolder.getRootMessages()) {
String fullName = rootMessage.getFullName();
if (!indexedEntityTypes.contains(fullName)) {
continue;
}
existIndexedEntities = true;
programmaticMapping.type(fullName)
.binder(new ProtobufMessageBinder(globalReferenceHolder, fullName))
.indexed().index(rootMessage.getIndexName());
builder.addEntityType(byte[].class, fullName);
}
return existIndexedEntities ? builder : null;
}
}
| 2,471
| 48.44
| 125
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/mapping/reference/MessageReferenceProvider.java
|
package org.infinispan.query.remote.impl.mapping.reference;
import static org.infinispan.query.remote.impl.indexing.IndexingMetadata.findProcessedAnnotation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.hibernate.search.engine.backend.document.IndexFieldReference;
import org.hibernate.search.engine.backend.document.model.dsl.IndexSchemaElement;
import org.hibernate.search.engine.backend.types.ObjectStructure;
import org.infinispan.api.annotations.indexing.option.Structure;
import org.infinispan.protostream.descriptors.Descriptor;
import org.infinispan.protostream.descriptors.FieldDescriptor;
import org.infinispan.protostream.descriptors.Type;
import org.infinispan.query.remote.impl.indexing.FieldMapping;
import org.infinispan.query.remote.impl.indexing.IndexingMetadata;
/**
* Provides indexing information about a {@link Descriptor}.
*
* @since 12.0
*/
public class MessageReferenceProvider {
public static final Set<String> COMMON_MESSAGE_TYPES =
new HashSet<>(Arrays.asList(FieldReferenceProvider.COMMON_MESSAGE_TYPES));
private final List<FieldReferenceProvider> fields;
private final List<Embedded> embedded;
public MessageReferenceProvider(Descriptor descriptor) {
this.fields = new ArrayList<>(descriptor.getFields().size());
this.embedded = new ArrayList<>();
IndexingMetadata indexingMetadata = findProcessedAnnotation(descriptor, IndexingMetadata.INDEXED_ANNOTATION);
// Skip if not annotated with @Indexed
if (indexingMetadata == null) {
return;
}
for (FieldDescriptor fieldDescriptor : descriptor.getFields()) {
String fieldName = fieldDescriptor.getName();
FieldMapping fieldMapping = indexingMetadata.getFieldMapping(fieldName);
if (fieldMapping == null) {
// field model is not mapped
continue;
}
if (Type.MESSAGE.equals(fieldDescriptor.getType()) &&
!COMMON_MESSAGE_TYPES.contains(fieldDescriptor.getTypeName())) {
// If a protobuf field is a Message reference, only take it into account
// if the Message is @Indexed and has at least one @Field annotation
if (fieldMapping.searchable() && isIndexable(fieldDescriptor.getMessageType())) {
// Hibernate Search can handle the @Field regardless of its attributes
embedded.add(new Embedded(fieldName, fieldDescriptor.getMessageType().getFullName(),
fieldDescriptor.isRepeated(), fieldMapping));
}
continue;
}
FieldReferenceProvider fieldReferenceProvider = new FieldReferenceProvider(fieldDescriptor, fieldMapping);
if (!fieldReferenceProvider.nothingToBind()) {
fields.add(fieldReferenceProvider);
}
}
}
/**
* Checks if a Descriptors has the @Indexed annotation and at least one @Field
*/
private boolean isIndexable(Descriptor descriptor) {
IndexingMetadata indexingMetadata = findProcessedAnnotation(descriptor, IndexingMetadata.INDEXED_ANNOTATION);
if ( indexingMetadata == null ) {
return false;
}
for (FieldDescriptor fieldDescriptor : descriptor.getFields()) {
FieldMapping fieldMapping = indexingMetadata.getFieldMapping(fieldDescriptor.getName());
if (fieldMapping != null) {
return true;
}
}
return false;
}
public boolean isEmpty() {
return fields.isEmpty();
}
public HashMap<String, IndexFieldReference<?>> bind(IndexSchemaElement indexSchemaElement, String basePath) {
HashMap<String, IndexFieldReference<?>> result = new HashMap<>();
for (FieldReferenceProvider field : fields) {
String newPath = ("".equals(basePath)) ? field.getName() : basePath + "." + field.getName();
result.put(newPath, field.bind(indexSchemaElement));
}
return result;
}
public List<Embedded> getEmbedded() {
return embedded;
}
public static class Embedded {
private final String fieldName;
private final String typeFullName;
private final boolean repeated;
private final Integer includeDepth;
private final ObjectStructure structure;
public Embedded(String fieldName, String typeFullName, boolean repeated, FieldMapping fieldMapping) {
this.fieldName = fieldName;
this.typeFullName = typeFullName;
this.repeated = repeated;
this.includeDepth = fieldMapping.includeDepth();
this.structure = (fieldMapping.structure() == null) ? null:
(Structure.NESTED.equals(fieldMapping.structure())) ? ObjectStructure.NESTED : ObjectStructure.FLATTENED;
}
public String getFieldName() {
return fieldName;
}
public String getTypeFullName() {
return typeFullName;
}
public boolean isRepeated() {
return repeated;
}
public Integer getIncludeDepth() {
return includeDepth;
}
public ObjectStructure getStructure() {
return structure;
}
@Override
public String toString() {
return "{" +
"fieldName='" + fieldName + '\'' +
", typeName='" + typeFullName + '\'' +
'}';
}
}
@Override
public String toString() {
return "{" +
"fields=" + fields +
", embedded=" + embedded +
'}';
}
}
| 5,595
| 33.975
| 120
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/mapping/reference/FieldReferenceProvider.java
|
package org.infinispan.query.remote.impl.mapping.reference;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.hibernate.search.backend.lucene.analysis.model.impl.LuceneAnalysisDefinitionRegistry;
import org.hibernate.search.backend.lucene.types.dsl.impl.LuceneIndexFieldTypeFactoryImpl;
import org.hibernate.search.engine.backend.document.IndexFieldReference;
import org.hibernate.search.engine.backend.document.model.dsl.IndexSchemaElement;
import org.hibernate.search.engine.backend.document.model.dsl.IndexSchemaFieldOptionsStep;
import org.hibernate.search.engine.backend.types.Aggregable;
import org.hibernate.search.engine.backend.types.Norms;
import org.hibernate.search.engine.backend.types.Projectable;
import org.hibernate.search.engine.backend.types.Searchable;
import org.hibernate.search.engine.backend.types.Sortable;
import org.hibernate.search.engine.backend.types.TermVector;
import org.hibernate.search.engine.backend.types.dsl.IndexFieldTypeFactory;
import org.hibernate.search.engine.backend.types.dsl.IndexFieldTypeFinalStep;
import org.hibernate.search.engine.backend.types.dsl.ScaledNumberIndexFieldTypeOptionsStep;
import org.hibernate.search.engine.backend.types.dsl.StandardIndexFieldTypeOptionsStep;
import org.hibernate.search.engine.backend.types.dsl.StringIndexFieldTypeOptionsStep;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.protostream.descriptors.FieldDescriptor;
import org.infinispan.protostream.descriptors.Type;
import org.infinispan.query.remote.impl.indexing.FieldMapping;
import org.infinispan.query.remote.impl.logging.Log;
public class FieldReferenceProvider {
private static final Log log = LogFactory.getLog(FieldReferenceProvider.class, Log.class);
public static final String INFINISPAN_COMMON_TYPES_GROUP = "org.infinispan.protostream.commons.";
public static final String BIG_INTEGER_COMMON_TYPE = INFINISPAN_COMMON_TYPES_GROUP + "BigInteger";
public static final String BIG_DECIMAL_COMMON_TYPE = INFINISPAN_COMMON_TYPES_GROUP + "BigDecimal";
static final String[] COMMON_MESSAGE_TYPES = {BIG_INTEGER_COMMON_TYPE, BIG_DECIMAL_COMMON_TYPE};
private final String name;
private final Type type;
private final String typeName;
private final boolean repeated;
private final Searchable searchable;
private final Projectable projectable;
private final Aggregable aggregable;
private final Sortable sortable;
private final String analyzer;
private final String normalizer;
private final Object indexNullAs;
private final Norms norms;
private final String searchAnalyzer;
private final TermVector termVector;
private final Integer decimalScale;
public FieldReferenceProvider(FieldDescriptor fieldDescriptor, FieldMapping fieldMapping) {
// the property name and type are taken from the model
name = fieldDescriptor.getName();
type = fieldDescriptor.getType();
typeName = fieldDescriptor.getTypeName();
repeated = fieldDescriptor.isRepeated();
searchable = (fieldMapping.searchable()) ? Searchable.YES : Searchable.NO;
projectable = (fieldMapping.projectable()) ? Projectable.YES : Projectable.NO;
aggregable = (fieldMapping.aggregable()) ? Aggregable.YES : Aggregable.NO;
sortable = (fieldMapping.sortable()) ? Sortable.YES : Sortable.NO;
analyzer = fieldMapping.analyzer();
normalizer = fieldMapping.normalizer();
indexNullAs = fieldMapping.parseIndexNullAs();
norms = (fieldMapping.norms() == null) ? null : (fieldMapping.norms()) ? Norms.YES : Norms.NO;
searchAnalyzer = fieldMapping.searchAnalyzer();
termVector = termVector(fieldMapping.termVector());
decimalScale = fieldMapping.decimalScale();
}
private static TermVector termVector(org.infinispan.api.annotations.indexing.option.TermVector termVector) {
if (termVector == null) {
return null;
}
switch (termVector) {
case YES:
return TermVector.YES;
case NO:
return TermVector.NO;
case WITH_POSITIONS:
return TermVector.WITH_POSITIONS;
case WITH_OFFSETS:
return TermVector.WITH_OFFSETS;
case WITH_POSITIONS_OFFSETS:
return TermVector.WITH_POSITIONS_OFFSETS;
case WITH_POSITIONS_PAYLOADS:
return TermVector.WITH_POSITIONS_PAYLOADS;
case WITH_POSITIONS_OFFSETS_PAYLOADS:
return TermVector.WITH_POSITIONS_OFFSETS_PAYLOADS;
}
return null;
}
public String getName() {
return name;
}
public IndexFieldReference<Object> bind(IndexSchemaElement indexSchemaElement) {
if (nothingToBind()) {
return null;
}
IndexSchemaFieldOptionsStep<?, IndexFieldReference<Object>> step = indexSchemaElement.field(name, this::bind);
if (repeated) {
step.multiValued();
}
return step.toReference();
}
public boolean nothingToBind() {
return Searchable.NO.equals(searchable) && Projectable.NO.equals(projectable) &&
Aggregable.NO.equals(aggregable) && Sortable.NO.equals(sortable);
}
private <F> IndexFieldTypeFinalStep<F> bind(IndexFieldTypeFactory typeFactory) {
StandardIndexFieldTypeOptionsStep<?, F> optionsStep = (StandardIndexFieldTypeOptionsStep<?, F>) bindType(typeFactory);
optionsStep.searchable(searchable).sortable(sortable).projectable(projectable).aggregable(aggregable);
if (indexNullAs != null) {
optionsStep.indexNullAs((F) indexNullAs);
}
return optionsStep;
}
private StandardIndexFieldTypeOptionsStep<?, ?> bindType(IndexFieldTypeFactory typeFactory) {
switch (type.getJavaType()) {
case ENUM:
case INT:
return typeFactory.asInteger();
case LONG:
return typeFactory.asLong();
case FLOAT:
return typeFactory.asFloat();
case DOUBLE:
return typeFactory.asDouble();
case BOOLEAN:
return typeFactory.asBoolean();
case STRING: {
StringIndexFieldTypeOptionsStep<?> step = typeFactory.asString();
bindStringTypeOptions(typeFactory, step);
return step;
}
case BYTE_STRING:
return typeFactory.asString();
case MESSAGE:
return bindCommonMessageType(typeFactory);
default:
throw log.fieldTypeNotIndexable(type.toString(), name);
}
}
private StandardIndexFieldTypeOptionsStep<?, ?> bindCommonMessageType(IndexFieldTypeFactory typeFactory) {
if (BIG_INTEGER_COMMON_TYPE.equals(typeName)) {
ScaledNumberIndexFieldTypeOptionsStep<?, BigInteger> step = typeFactory.asBigInteger();
bindScaledNumberTypeOptions(step);
return step;
}
if (BIG_DECIMAL_COMMON_TYPE.equals(typeName)) {
ScaledNumberIndexFieldTypeOptionsStep<?, BigDecimal> step = typeFactory.asBigDecimal();
bindScaledNumberTypeOptions(step);
return step;
}
throw log.fieldTypeNotIndexable(typeName, name);
}
private void bindScaledNumberTypeOptions(ScaledNumberIndexFieldTypeOptionsStep<?, ?> step) {
if (decimalScale != null) {
step.decimalScale(decimalScale);
} else {
step.decimalScale(0); // if a basic is used
}
}
private void bindStringTypeOptions(IndexFieldTypeFactory typeFactory, StringIndexFieldTypeOptionsStep<?> step) {
bindNormalizerOrAnalyzer((LuceneIndexFieldTypeFactoryImpl) typeFactory, step);
if (norms != null) {
step.norms(norms);
}
if (searchAnalyzer != null) {
step.searchAnalyzer(searchAnalyzer);
}
if (termVector != null) {
step.termVector(termVector);
}
}
private void bindNormalizerOrAnalyzer(LuceneIndexFieldTypeFactoryImpl typeFactory, StringIndexFieldTypeOptionsStep<?> step) {
if (normalizer != null) {
step.normalizer(normalizer);
return;
}
// TODO the following algorithm is used to support normalizer using legacy annotation,
// this won't be necessary when they are removed.
if (analyzer == null) {
return;
}
LuceneAnalysisDefinitionRegistry analysisDefinitionRegistry = typeFactory.getAnalysisDefinitionRegistry();
if (analysisDefinitionRegistry.getNormalizerDefinition(analyzer) != null) {
step.normalizer(analyzer);
} else {
step.analyzer(analyzer);
}
}
@Override
public String toString() {
return "{" +
"name='" + name + '\'' +
", type=" + type +
'}';
}
}
| 8,722
| 38.116592
| 128
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/mapping/reference/IndexReferenceHolder.java
|
package org.infinispan.query.remote.impl.mapping.reference;
import java.util.Map;
import org.hibernate.search.engine.backend.document.IndexFieldReference;
import org.hibernate.search.engine.backend.document.IndexObjectFieldReference;
public class IndexReferenceHolder {
private final Map<String, IndexFieldReference<?>> fieldReferenceMap;
private final Map<String, IndexObjectFieldReference> objectReferenceMap;
public IndexReferenceHolder(Map<String, IndexFieldReference<?>> fieldReferenceMap, Map<String, IndexObjectFieldReference> objectReferenceMap) {
this.fieldReferenceMap = fieldReferenceMap;
this.objectReferenceMap = objectReferenceMap;
}
public IndexFieldReference<?> getFieldReference(String absoluteFieldPath) {
return fieldReferenceMap.get(absoluteFieldPath);
}
public IndexObjectFieldReference getObjectReference(String absoluteObjectFieldPath) {
return objectReferenceMap.get(absoluteObjectFieldPath);
}
}
| 976
| 36.576923
| 146
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/mapping/reference/GlobalReferenceHolder.java
|
package org.infinispan.query.remote.impl.mapping.reference;
import static org.infinispan.query.remote.impl.indexing.IndexingMetadata.findProcessedAnnotation;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.infinispan.protostream.descriptors.Descriptor;
import org.infinispan.protostream.descriptors.GenericDescriptor;
import org.infinispan.query.remote.impl.indexing.IndexingMetadata;
public class GlobalReferenceHolder {
private final Map<String, MessageReferenceProvider> messageReferenceProviders = new HashMap<>();
private final Set<RootMessageInfo> rootMessages = new LinkedHashSet<>();
private final Map<String, Descriptor> rootDescriptors = new HashMap<>();
public GlobalReferenceHolder(Map<String, GenericDescriptor> descriptors) {
HashSet<Descriptor> messageTypes = new HashSet<>();
HashSet<Descriptor> nestedDescriptors = new HashSet<>();
for (Map.Entry<String, GenericDescriptor> entry : descriptors.entrySet()) {
GenericDescriptor genericDescriptor = entry.getValue();
if (!(genericDescriptor instanceof Descriptor)) {
// skip enum types, they are mapped as strings
continue;
}
Descriptor descriptor = (Descriptor) genericDescriptor;
MessageReferenceProvider messageReferenceProvider = new MessageReferenceProvider(descriptor);
if (messageReferenceProvider.isEmpty()) {
// skip not indexed types
continue;
}
messageReferenceProviders.put(entry.getKey(), messageReferenceProvider);
messageTypes.add(descriptor);
nestedDescriptors.addAll(descriptor.getNestedTypes());
}
messageTypes.removeAll(nestedDescriptors);
for (Descriptor descriptor : messageTypes) {
rootMessages.add(new RootMessageInfo(descriptor));
rootDescriptors.put(descriptor.getFullName(), descriptor);
}
}
public Map<String, MessageReferenceProvider> getMessageReferenceProviders() {
return messageReferenceProviders;
}
public Set<RootMessageInfo> getRootMessages() {
return rootMessages;
}
public Descriptor getDescriptor(String fullName) {
return rootDescriptors.get(fullName);
}
@Override
public String toString() {
return messageReferenceProviders.toString();
}
public static class RootMessageInfo {
private final String fullName;
private final String indexName;
private RootMessageInfo(Descriptor descriptor) {
IndexingMetadata indexingMetadata = findProcessedAnnotation(descriptor, IndexingMetadata.INDEXED_ANNOTATION);
this.fullName = descriptor.getFullName();
this.indexName = (indexingMetadata.indexName() != null) ? indexingMetadata.indexName() : fullName;
}
public String getFullName() {
return fullName;
}
public String getIndexName() {
return indexName;
}
}
}
| 3,022
| 33.747126
| 119
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/mapping/typebridge/ProtobufMessageBinder.java
|
package org.infinispan.query.remote.impl.mapping.typebridge;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import org.hibernate.search.engine.backend.document.IndexFieldReference;
import org.hibernate.search.engine.backend.document.IndexObjectFieldReference;
import org.hibernate.search.engine.backend.document.model.dsl.IndexSchemaElement;
import org.hibernate.search.engine.backend.document.model.dsl.IndexSchemaObjectField;
import org.hibernate.search.engine.backend.types.ObjectStructure;
import org.hibernate.search.mapper.pojo.bridge.binding.TypeBindingContext;
import org.hibernate.search.mapper.pojo.bridge.mapping.programmatic.TypeBinder;
import org.infinispan.protostream.descriptors.Descriptor;
import org.infinispan.query.remote.impl.mapping.reference.GlobalReferenceHolder;
import org.infinispan.query.remote.impl.mapping.reference.IndexReferenceHolder;
import org.infinispan.query.remote.impl.mapping.reference.MessageReferenceProvider;
public class ProtobufMessageBinder implements TypeBinder {
private final GlobalReferenceHolder globalReferenceHolder;
private final String rootMessageName;
public ProtobufMessageBinder(GlobalReferenceHolder globalReferenceHolder, String rootMessageName) {
this.globalReferenceHolder = globalReferenceHolder;
this.rootMessageName = rootMessageName;
}
@Override
public void bind(TypeBindingContext context) {
context.dependencies().useRootOnly();
IndexReferenceHolder indexReferenceProvider = createIndexReferenceProvider(context);
Descriptor descriptor = globalReferenceHolder.getDescriptor(rootMessageName);
context.bridge(byte[].class, new ProtobufMessageBridge(indexReferenceProvider, descriptor));
}
private IndexReferenceHolder createIndexReferenceProvider(TypeBindingContext context) {
final Map<String, IndexFieldReference<?>> fieldReferenceMap = new HashMap<>();
final Map<String, IndexObjectFieldReference> objectReferenceMap = new HashMap<>();
Stack<State> stack = new Stack<>();
stack.push(new State(globalReferenceHolder.getMessageReferenceProviders().get(rootMessageName),
"", context.indexSchemaElement(), 0));
Integer maxDepth = null;
while (!stack.isEmpty()) {
State currentState = stack.pop();
fieldReferenceMap.putAll(currentState.bind());
if (maxDepth != null && currentState.depth == maxDepth) {
continue;
}
for (MessageReferenceProvider.Embedded embedded : currentState.messageReferenceProvider.getEmbedded()) {
String newPath = ("".equals(currentState.path)) ? embedded.getFieldName() :
currentState.path + "." + embedded.getFieldName();
maxDepth = embedded.getIncludeDepth();
String typeName = embedded.getTypeFullName();
MessageReferenceProvider messageReferenceProvider = globalReferenceHolder.getMessageReferenceProviders().get(typeName);
ObjectStructure structure = embedded.getStructure();
if (structure == null) {
structure = ObjectStructure.FLATTENED; // for legacy annotations
}
IndexSchemaObjectField indexSchemaElement = currentState.indexSchemaElement
.objectField(embedded.getFieldName(), structure);
if (embedded.isRepeated()) {
indexSchemaElement.multiValued();
}
objectReferenceMap.put(newPath, indexSchemaElement.toReference());
State state = new State(messageReferenceProvider, newPath, indexSchemaElement, currentState.depth + 1);
stack.push(state);
}
}
return new IndexReferenceHolder(fieldReferenceMap, objectReferenceMap);
}
private static class State {
private final MessageReferenceProvider messageReferenceProvider;
private final String path;
private final IndexSchemaElement indexSchemaElement;
private final int depth;
public State(MessageReferenceProvider messageReferenceProvider, String path,
IndexSchemaElement indexSchemaElement, int depth) {
this.messageReferenceProvider = messageReferenceProvider;
this.path = path;
this.indexSchemaElement = indexSchemaElement;
this.depth = depth;
}
public Map<String, IndexFieldReference<?>> bind() {
return messageReferenceProvider.bind(indexSchemaElement, path);
}
}
}
| 4,488
| 43.009804
| 131
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/mapping/typebridge/ProtobufMessageBridge.java
|
package org.infinispan.query.remote.impl.mapping.typebridge;
import java.io.IOException;
import org.hibernate.search.engine.backend.document.DocumentElement;
import org.hibernate.search.mapper.pojo.bridge.TypeBridge;
import org.hibernate.search.mapper.pojo.bridge.runtime.TypeBridgeWriteContext;
import org.infinispan.protostream.ProtobufParser;
import org.infinispan.protostream.descriptors.Descriptor;
import org.infinispan.query.remote.impl.indexing.IndexingTagHandler;
import org.infinispan.query.remote.impl.mapping.reference.IndexReferenceHolder;
public class ProtobufMessageBridge implements TypeBridge<byte[]> {
private final IndexReferenceHolder indexReferenceHolder;
private final Descriptor descriptor;
ProtobufMessageBridge(IndexReferenceHolder indexReferenceHolder, Descriptor descriptor) {
this.indexReferenceHolder = indexReferenceHolder;
this.descriptor = descriptor;
}
@Override
public void write(DocumentElement target, byte[] messageBytes, TypeBridgeWriteContext context) {
IndexingTagHandler tagHandler = new IndexingTagHandler(descriptor, target, indexReferenceHolder);
try {
ProtobufParser.INSTANCE.parse(tagHandler, descriptor, messageBytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 1,301
| 37.294118
| 103
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/mapping/model/ProtobufBootstrapIntrospector.java
|
package org.infinispan.query.remote.impl.mapping.model;
import java.lang.invoke.MethodHandles;
import org.hibernate.search.mapper.pojo.model.spi.PojoBootstrapIntrospector;
import org.hibernate.search.mapper.pojo.model.spi.PojoRawTypeModel;
import org.hibernate.search.util.common.reflect.spi.ValueHandleFactory;
import org.hibernate.search.util.common.reflect.spi.ValueReadHandleFactory;
import org.infinispan.search.mapper.mapping.SearchMappingBuilder;
public class ProtobufBootstrapIntrospector implements PojoBootstrapIntrospector {
private final PojoBootstrapIntrospector delegate = SearchMappingBuilder.introspector(MethodHandles.lookup());
@Override
public <T> PojoRawTypeModel<T> typeModel(Class<T> clazz) {
return delegate.typeModel(clazz);
}
@Override
public PojoRawTypeModel<?> typeModel(String name) {
return new ProtobufRawTypeModel(typeModel(byte[].class), name);
}
@Override
public ValueHandleFactory annotationValueHandleFactory() {
return delegate.annotationValueHandleFactory();
}
@Override
public ValueReadHandleFactory annotationValueReadHandleFactory() {
return delegate.annotationValueReadHandleFactory();
}
}
| 1,202
| 33.371429
| 112
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/mapping/model/ProtobufRawTypeModel.java
|
package org.infinispan.query.remote.impl.mapping.model;
import java.lang.annotation.Annotation;
import java.util.Collection;
import java.util.Collections;
import java.util.Objects;
import java.util.Optional;
import java.util.StringJoiner;
import java.util.stream.Stream;
import org.hibernate.search.engine.mapper.model.spi.MappableTypeModel;
import org.hibernate.search.mapper.pojo.model.spi.JavaClassPojoCaster;
import org.hibernate.search.mapper.pojo.model.spi.PojoCaster;
import org.hibernate.search.mapper.pojo.model.spi.PojoConstructorModel;
import org.hibernate.search.mapper.pojo.model.spi.PojoPropertyModel;
import org.hibernate.search.mapper.pojo.model.spi.PojoRawTypeIdentifier;
import org.hibernate.search.mapper.pojo.model.spi.PojoRawTypeModel;
import org.hibernate.search.mapper.pojo.model.spi.PojoTypeModel;
public class ProtobufRawTypeModel implements PojoRawTypeModel<byte[]> {
private final PojoRawTypeModel<byte[]> superType;
private final PojoRawTypeIdentifier<byte[]> typeIdentifier;
private final PojoCaster<byte[]> caster;
public ProtobufRawTypeModel(PojoRawTypeModel<byte[]> superType, String name) {
this.superType = superType;
this.typeIdentifier = PojoRawTypeIdentifier.of(byte[].class, name);
this.caster = new JavaClassPojoCaster<>(byte[].class);
}
@Override
public PojoRawTypeIdentifier<byte[]> typeIdentifier() {
return typeIdentifier;
}
@Override
public boolean isAbstract() {
// Protocol Buffers does not support abstract classes.
return false;
}
@Override
public boolean isSubTypeOf(MappableTypeModel superTypeCandidate) {
return equals(superTypeCandidate) || superType.isSubTypeOf(superTypeCandidate);
}
@Override
public Stream<? extends PojoRawTypeModel<? super byte[]>> ascendingSuperTypes() {
return Stream.concat(Stream.of(this), superType.ascendingSuperTypes());
}
@Override
public Stream<? extends PojoRawTypeModel<? super byte[]>> descendingSuperTypes() {
return Stream.concat(superType.descendingSuperTypes(), Stream.of(this));
}
@Override
public Stream<Annotation> annotations() {
// Mapping is defined programmatically (at the moment)
return Stream.empty();
}
@Override
public PojoConstructorModel<byte[]> mainConstructor() {
return null;
}
@Override
public PojoConstructorModel<byte[]> constructor(Class<?>... parameterTypes) {
return null;
}
@Override
public Collection<PojoConstructorModel<byte[]>> declaredConstructors() {
// No support for constructors on dynamic-map types.
return Collections.emptyList();
}
@Override
public Collection<PojoPropertyModel<?>> declaredProperties() {
// Properties are created by ProtobufMessageBinder
return Collections.emptySet();
}
@Override
public PojoTypeModel<? extends byte[]> cast(PojoTypeModel<?> other) {
if ( other.rawType().isSubTypeOf( this ) ) {
// Redundant cast; no need to create a new type.
return (PojoTypeModel<? extends byte[]>) other;
}
else {
// There is no generic type information to retain for protobuf types; we can just return this.
// Also, calling other.castTo(...) would mean losing the type name, and we definitely don't want that.
return this;
}
}
@Override
public PojoCaster<byte[]> caster() {
return caster;
}
@Override
public String name() {
return typeIdentifier.toString();
}
@Override
public PojoRawTypeModel<byte[]> rawType() {
return this;
}
@Override
public PojoPropertyModel<?> property(String propertyName) {
// Properties are created by ProtobufMessageBinder
return null;
}
@Override
public <U> Optional<PojoTypeModel<? extends U>> castTo(Class<U> target) {
return Optional.empty();
}
@Override
public Optional<? extends PojoTypeModel<?>> typeArgument(Class<?> rawSuperType, int typeParameterIndex) {
return Optional.empty();
}
@Override
public Optional<? extends PojoTypeModel<?>> arrayElementType() {
return Optional.empty();
}
@Override
public String toString() {
return new StringJoiner(", ", ProtobufRawTypeModel.class.getSimpleName() + "[", "]").add("typeIdentifier=" + typeIdentifier).toString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ProtobufRawTypeModel that = (ProtobufRawTypeModel) o;
return Objects.equals(typeIdentifier, that.typeIdentifier);
}
@Override
public int hashCode() {
return Objects.hash(typeIdentifier);
}
}
| 4,776
| 29.426752
| 142
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/json/JsonQueryRequest.java
|
package org.infinispan.query.remote.json;
import static org.infinispan.query.remote.json.JSONConstants.HIT_COUNT_ACCURACY;
import static org.infinispan.query.remote.json.JSONConstants.MAX_RESULTS;
import static org.infinispan.query.remote.json.JSONConstants.OFFSET;
import static org.infinispan.query.remote.json.JSONConstants.QUERY_STRING;
import java.util.Map;
import org.infinispan.commons.dataconversion.internal.Json;
import org.infinispan.commons.dataconversion.internal.JsonSerialization;
/**
* @since 9.4
*/
public class JsonQueryRequest implements JsonSerialization {
private static final Integer DEFAULT_OFFSET = 0;
private static final Integer DEFAULT_MAX_RESULTS = 10;
private final String query;
private final Integer startOffset;
private final Integer maxResults;
private Integer hitCountAccuracy;
public JsonQueryRequest(String query, Integer startOffset, Integer maxResults, Integer hitCountAccuracy) {
this.query = query;
this.startOffset = startOffset == null ? DEFAULT_OFFSET : startOffset;
this.maxResults = maxResults == null ? DEFAULT_MAX_RESULTS : maxResults;
this.hitCountAccuracy = hitCountAccuracy;
}
public String getQuery() {
return query;
}
public Integer getStartOffset() {
return startOffset;
}
public Integer getMaxResults() {
return maxResults;
}
public Integer getHitCountAccuracy() {
return hitCountAccuracy;
}
public void setDefaultHitCountAccuracy(int defaultHitCountAccuracy) {
if (hitCountAccuracy == null) {
hitCountAccuracy = defaultHitCountAccuracy;
}
}
@Override
public Json toJson() {
throw new UnsupportedOperationException();
}
public static JsonQueryRequest fromJson(String json) {
Map<String, Json> properties = Json.read(json).asJsonMap();
Json queryValue = properties.get(QUERY_STRING);
Json offsetValue = properties.get(OFFSET);
Json maxResultsValue = properties.get(MAX_RESULTS);
Json hitCountAccuracyValue = properties.get(HIT_COUNT_ACCURACY);
String query = queryValue != null ? queryValue.asString() : null;
Integer offset = offsetValue != null ? offsetValue.asInteger() : null;
Integer maxResults = maxResultsValue != null ? maxResultsValue.asInteger() : null;
Integer hitCountAccuracy = hitCountAccuracyValue != null ? hitCountAccuracyValue.asInteger() : null;
return new JsonQueryRequest(query, offset, maxResults, hitCountAccuracy);
}
}
| 2,518
| 32.586667
| 109
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/json/JSONConstants.java
|
package org.infinispan.query.remote.json;
/**
* @since 9.4
*/
public interface JSONConstants {
String ERROR = "error";
String MESSAGE = "message";
String CAUSE = "cause";
String HIT = "hit";
String HITS = "hits";
String MAX_RESULTS = "max_results";
String OFFSET = "offset";
String HIT_COUNT_ACCURACY = "hit_count_accuracy";
String QUERY_STRING = "query";
String HIT_COUNT = "hit_count";
String HIT_COUNT_EXACT = "hit_count_exact";
String TYPE = "_type";
}
| 496
| 23.85
| 52
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/json/JsonQueryResponse.java
|
package org.infinispan.query.remote.json;
import org.infinispan.commons.dataconversion.internal.JsonSerialization;
/**
* @since 9.4
*/
public abstract class JsonQueryResponse implements JsonSerialization {
private final int hitCount;
private final boolean hitCountExact;
JsonQueryResponse(int hitCount, boolean hitCountExact) {
this.hitCount = hitCount;
this.hitCountExact = hitCountExact;
}
public int hitCount() {
return hitCount;
}
public boolean hitCountExact() {
return hitCountExact;
}
}
| 550
| 20.192308
| 72
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/json/JsonQueryResult.java
|
package org.infinispan.query.remote.json;
import static org.infinispan.query.remote.json.JSONConstants.HITS;
import static org.infinispan.query.remote.json.JSONConstants.HIT_COUNT;
import static org.infinispan.query.remote.json.JSONConstants.HIT_COUNT_EXACT;
import java.util.List;
import org.infinispan.commons.dataconversion.internal.Json;
/**
* @since 9.4
*/
public class JsonQueryResult extends JsonQueryResponse {
private final List<Hit> hits;
public JsonQueryResult(List<Hit> hits, int hitCount, boolean hitCountExact) {
super(hitCount, hitCountExact);
this.hits = hits;
}
public List<Hit> getHits() {
return hits;
}
@Override
public Json toJson() {
Json object = Json.object();
object.set(HIT_COUNT, hitCount());
object.set(HIT_COUNT_EXACT, hitCountExact());
Json array = Json.array();
hits.forEach(hit -> array.add(Json.factory().raw(hit.toJson().toString())));
object.set(HITS, array);
return object;
}
}
| 1,008
| 25.552632
| 82
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/json/Hit.java
|
package org.infinispan.query.remote.json;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.infinispan.query.remote.json.JSONConstants.HIT;
import org.infinispan.commons.dataconversion.internal.JsonSerialization;
import org.infinispan.commons.dataconversion.internal.Json;
/**
* Represents each of the search results.
*
* @since 9.4
*/
public class Hit implements JsonSerialization {
private final Object value;
public Hit(Object value) {
this.value = value;
}
public Object getValue() {
return value;
}
@Override
public Json toJson() {
String rawJson = value instanceof String ? value.toString() : new String((byte[]) value, UTF_8);
return Json.object().set(HIT, Json.factory().raw(rawJson));
}
}
| 781
| 22.69697
| 102
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/json/JsonQueryErrorResult.java
|
package org.infinispan.query.remote.json;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.infinispan.query.remote.json.JSONConstants.CAUSE;
import static org.infinispan.query.remote.json.JSONConstants.MESSAGE;
import org.infinispan.commons.dataconversion.internal.JsonSerialization;
import org.infinispan.commons.dataconversion.internal.Json;
public class JsonQueryErrorResult implements JsonSerialization {
private final String message;
private final String cause;
public JsonQueryErrorResult(String message, String cause) {
this.message = message;
this.cause = cause;
}
@Override
public Json toJson() {
return Json.object().set(JSONConstants.ERROR, Json.object().set(MESSAGE, message).set(CAUSE, cause));
}
public byte[] asBytes() {
return toJson().toString().getBytes(UTF_8);
}
}
| 865
| 29.928571
| 107
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/json/ProjectedJsonResult.java
|
package org.infinispan.query.remote.json;
import static org.infinispan.query.remote.json.JSONConstants.HITS;
import static org.infinispan.query.remote.json.JSONConstants.HIT_COUNT;
import static org.infinispan.query.remote.json.JSONConstants.HIT_COUNT_EXACT;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.infinispan.commons.dataconversion.internal.Json;
/**
* @since 9.4
*/
public class ProjectedJsonResult extends JsonQueryResponse {
private final List<JsonProjection> hits;
public ProjectedJsonResult(int hitCount, boolean hitCountExact, String[] projections, List<Object> values) {
super(hitCount, hitCountExact);
hits = new ArrayList<>(projections.length);
for (Object v : values) {
Object[] result = (Object[]) v;
Map<String, Object> p = new HashMap<>();
for (int i = 0; i < projections.length; i++) {
p.put(projections[i], result[i]);
}
hits.add(new JsonProjection(p));
}
}
public List<JsonProjection> getHits() {
return hits;
}
@Override
public Json toJson() {
Json object = Json.object();
object.set(HIT_COUNT, hitCount());
object.set(HIT_COUNT_EXACT, hitCountExact());
Json array = Json.array();
hits.forEach(h -> array.add(Json.factory().raw(h.toJson().toString())));
return object.set(HITS, array);
}
}
| 1,435
| 28.916667
| 111
|
java
|
null |
infinispan-main/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/json/JsonProjection.java
|
package org.infinispan.query.remote.json;
import static org.infinispan.query.remote.json.JSONConstants.HIT;
import java.util.Map;
import org.infinispan.commons.dataconversion.internal.JsonSerialization;
import org.infinispan.commons.dataconversion.internal.Json;
/**
* @since 9.4
*/
public class JsonProjection implements JsonSerialization {
private final Map<String, Object> value;
JsonProjection(Map<String, Object> value) {
this.value = value;
}
public Map<String, Object> getValue() {
return value;
}
@Override
public Json toJson() {
return Json.object().set(HIT, Json.make(value));
}
}
| 643
| 20.466667
| 72
|
java
|
null |
infinispan-main/remote-query/remote-query-client/src/main/java/org/infinispan/query/remote/client/package-info.java
|
/**
* Query client support classes.
*
* @api.public
*/
package org.infinispan.query.remote.client;
| 103
| 13.857143
| 43
|
java
|
null |
infinispan-main/remote-query/remote-query-client/src/main/java/org/infinispan/query/remote/client/ProtobufMetadataManagerMBean.java
|
package org.infinispan.query.remote.client;
/**
* MBean interface for ProtobufMetadataManager, suitable for building invocation proxies with one of the {@link
* javax.management.JMX#newMBeanProxy} methods.
*
* @author anistor@redhat.com
* @author gustavonalle
* @since 7.1
*/
public interface ProtobufMetadataManagerMBean extends ProtobufMetadataManagerConstants {
/**
* Register a *.proto schema file. If there are any syntax or semantic errors a *.proto.errors key will be created in
* the underlying cache and its value will be the actual error message. The error message, if any, can be retrieved
* using {@link #getFileErrors(String fileName)} method. The list of offending files can be retrieved using {@link
* #getFilesWithErrors()} method.
*
* @param fileName the full name of the file (name can contain '/'); must end with ".proto" suffix
* @param contents the file contents
* @throws Exception in case of failure
*/
void registerProtofile(String fileName, String contents) throws Exception;
/**
* Registers multiple *.proto schema files. If there are any syntax or semantic errors a *.proto.errors key will be
* created in the underlying cache for each offending file and its value will be the actual error message. The error
* message, if any, can be retrieved using {@link #getFileErrors(String fileName)} method. The list of offending
* files can be retrieved using {@link #getFilesWithErrors()} method.
*
* @param fileNames the full names of the files (name can contain '/'); names must end with ".proto" suffix
* @param contents the contents of each file; this array must have the same length as {@code fileNames}
* @throws Exception in case of failure
*/
void registerProtofiles(String[] fileNames, String[] contents) throws Exception;
/**
* Unregister a *.proto schema file.
*
* @param fileName the full name of the file (name can contain '/'); must end with ".proto" suffix
* @throws Exception in case of failure
*/
void unregisterProtofile(String fileName) throws Exception;
/**
* Unregisters multiple *.proto schema files.
*
* @param fileNames the full names of the files (name can contain '/'); names must end with ".proto" suffix
* @throws Exception in case of failure
*/
void unregisterProtofiles(String[] fileNames) throws Exception;
/**
* Get the full names of all registered schema files.
*
* @return the array of all registered schema file names or an empty array if there are no files (never null)
*/
String[] getProtofileNames();
/**
* Gets the contents of a registered *.proto schema file.
*
* @param fileName the name of the file; must end with ".proto" suffix
* @return the file contents or {@code null} if the file does not exist
*/
String getProtofile(String fileName);
/**
* Get the full names of all files with errors.
*
* @return the array of all file names with errors or an empty array if there are no files with errors (never null)
*/
String[] getFilesWithErrors();
/**
* Gets the error messages (caused by parsing, linking, etc) associated to a *.proto schema file.
*
* @param fileName the name of the file; must end with ".proto" suffix
* @return the error text or {@code null} if there are no errors
*/
String getFileErrors(String fileName);
}
| 3,436
| 40.409639
| 120
|
java
|
null |
infinispan-main/remote-query/remote-query-client/src/main/java/org/infinispan/query/remote/client/ProtobufMetadataManagerConstants.java
|
package org.infinispan.query.remote.client;
/**
* Useful constants used by the Protobuf metadata cache.
*
* @author anistor@redhat.com
* @since 7.1
*/
public interface ProtobufMetadataManagerConstants {
/**
* The name of the Protobuf definitions cache.
*/
String PROTOBUF_METADATA_CACHE_NAME = "___protobuf_metadata";
/**
* All error status keys end with this suffix. This is also the name of the global error key.
*/
String ERRORS_KEY_SUFFIX = ".errors";
/**
* All protobuf definition source files must end with this suffix.
*/
String PROTO_KEY_SUFFIX = ".proto";
/**
* The 'component' key property of ProtobufMetadataManager's ObjectName.
*/
String OBJECT_NAME = "ProtobufMetadataManager";
}
| 760
| 23.548387
| 96
|
java
|
null |
infinispan-main/remote-query/remote-query-client/src/main/java/org/infinispan/query/remote/client/FilterResult.java
|
package org.infinispan.query.remote.client;
import java.util.Arrays;
/**
* When using Ickle based filters with client event listeners you will get the event data (see
* org.infinispan.client.hotrod.event.ClientCacheEntryCustomEvent.getEventData) wrapped by this FilterResult.
*
* @author anistor@redhat.com
* @since 7.2
*/
public final class FilterResult {
private final Object instance;
private final Object[] projection;
private final Comparable[] sortProjection;
public FilterResult(Object instance, Object[] projection, Comparable[] sortProjection) {
if (instance == null && projection == null) {
throw new IllegalArgumentException("instance and projection cannot be both null");
}
this.instance = instance;
this.projection = projection;
this.sortProjection = sortProjection;
}
/**
* Returns the matched object. This is non-null unless projections are present.
*/
public Object getInstance() {
return instance;
}
/**
* Returns the projection, if a projection was requested or {@code null} otherwise.
*/
public Object[] getProjection() {
return projection;
}
/**
* Returns the projection of fields that appear in the 'order by' clause, if any, or {@code null} otherwise.
* <p>
* Please note that no actual sorting is performed! The 'order by' clause is ignored but the fields listed there are
* still projected and returned so the caller can easily sort the results if needed. Do not use 'order by' with
* filters if this behaviour does not suit you.
*/
public Comparable[] getSortProjection() {
return sortProjection;
}
@Override
public String toString() {
return "FilterResult{" +
"instance=" + instance +
", projection=" + Arrays.toString(projection) +
", sortProjection=" + Arrays.toString(sortProjection) +
'}';
}
}
| 1,942
| 29.84127
| 119
|
java
|
null |
infinispan-main/remote-query/remote-query-client/src/main/java/org/infinispan/query/remote/client/impl/FilterResultMarshaller.java
|
package org.infinispan.query.remote.client.impl;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.infinispan.protostream.MessageMarshaller;
import org.infinispan.protostream.ProtobufUtil;
import org.infinispan.protostream.WrappedMessage;
import org.infinispan.query.remote.client.FilterResult;
/**
* Protostream marshaller for {@link FilterResult}.
*
* @author anistor@redhat.com
*/
final class FilterResultMarshaller implements MessageMarshaller<FilterResult> {
@Override
public FilterResult readFrom(ProtoStreamReader reader) throws IOException {
byte[] instance = reader.readBytes("instance");
List<WrappedMessage> projection = reader.readCollection("projection", new ArrayList<>(), WrappedMessage.class);
List<WrappedMessage> sortProjection = reader.readCollection("sortProjection", new ArrayList<>(), WrappedMessage.class);
Object i = null;
if (instance != null) {
i = ProtobufUtil.fromWrappedByteArray(reader.getSerializationContext(), instance);
}
Object[] p = null;
if (!projection.isEmpty()) {
p = new Object[projection.size()];
int j = 0;
for (WrappedMessage m : projection) {
p[j++] = m.getValue();
}
}
Comparable[] sp = null;
if (!sortProjection.isEmpty()) {
sp = new Comparable[sortProjection.size()];
int j = 0;
for (WrappedMessage m : sortProjection) {
sp[j++] = (Comparable) m.getValue();
}
}
return new FilterResult(i, p, sp);
}
@Override
public void writeTo(ProtoStreamWriter writer, FilterResult filterResult) throws IOException {
if (filterResult.getProjection() == null) {
// skip marshalling the instance if there is a projection
writer.writeBytes("instance", (byte[]) filterResult.getInstance());
} else {
WrappedMessage[] p = new WrappedMessage[filterResult.getProjection().length];
for (int i = 0; i < p.length; i++) {
p[i] = new WrappedMessage(filterResult.getProjection()[i]);
}
writer.writeArray("projection", p, WrappedMessage.class);
}
if (filterResult.getSortProjection() != null) {
WrappedMessage[] p = new WrappedMessage[filterResult.getSortProjection().length];
for (int i = 0; i < p.length; i++) {
p[i] = new WrappedMessage(filterResult.getSortProjection()[i]);
}
writer.writeArray("sortProjection", p, WrappedMessage.class);
}
}
@Override
public Class<FilterResult> getJavaClass() {
return FilterResult.class;
}
@Override
public String getTypeName() {
return "org.infinispan.query.remote.client.FilterResult";
}
}
| 2,782
| 32.53012
| 125
|
java
|
null |
infinispan-main/remote-query/remote-query-client/src/main/java/org/infinispan/query/remote/client/impl/package-info.java
|
/**
* Hot Rod query client side implementation details. This package is strictly for internal use.
*
* @api.private
*/
package org.infinispan.query.remote.client.impl;
| 172
| 23.714286
| 95
|
java
|
null |
infinispan-main/remote-query/remote-query-client/src/main/java/org/infinispan/query/remote/client/impl/MarshallerRegistration.java
|
package org.infinispan.query.remote.client.impl;
import org.infinispan.protostream.FileDescriptorSource;
import org.infinispan.protostream.SerializationContext;
import org.infinispan.protostream.SerializationContextInitializer;
/**
* Registers protobuf schemas and marshallers for the objects used by remote query, remote continuous query and Ickle
* based filters.
*
* @author anistor@redhat.com
* @since 6.0
*/
public final class MarshallerRegistration implements SerializationContextInitializer {
private static final String QUERY_PROTO_RES = "/org/infinispan/query/remote/client/query.proto";
public static final MarshallerRegistration INSTANCE = new MarshallerRegistration();
private MarshallerRegistration() {
}
@Override
public String getProtoFileName() {
return QUERY_PROTO_RES;
}
@Override
public String getProtoFile() {
return FileDescriptorSource.getResourceAsString(getClass(), QUERY_PROTO_RES);
}
@Override
public void registerSchema(SerializationContext serCtx) {
serCtx.registerProtoFiles(FileDescriptorSource.fromString(getProtoFileName(), getProtoFile()));
}
@Override
public void registerMarshallers(SerializationContext ctx) {
ctx.registerMarshaller(new QueryRequest.NamedParameter.Marshaller());
ctx.registerMarshaller(new QueryRequest.Marshaller());
ctx.registerMarshaller(new QueryResponse.Marshaller());
ctx.registerMarshaller(new FilterResultMarshaller());
ctx.registerMarshaller(new ContinuousQueryResult.ResultType.Marshaller());
ctx.registerMarshaller(new ContinuousQueryResult.Marshaller());
}
/**
* Registers proto files and marshallers.
*
* @param ctx the serialization context
*/
public static void init(SerializationContext ctx) {
INSTANCE.registerSchema(ctx);
INSTANCE.registerMarshallers(ctx);
}
}
| 1,887
| 31.551724
| 117
|
java
|
null |
infinispan-main/remote-query/remote-query-client/src/main/java/org/infinispan/query/remote/client/impl/Externalizers.java
|
package org.infinispan.query.remote.client.impl;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.List;
import org.infinispan.commons.marshall.Externalizer;
import org.infinispan.protostream.WrappedMessage;
/**
* jboss-marshalling externalizers for QueryRequest and QueryResponse objects.
*
* @author anistor@redhat.com
* @since 9.1
*/
public final class Externalizers {
private Externalizers() {
}
public static final class QueryRequestExternalizer implements Externalizer<QueryRequest> {
@Override
public void writeObject(ObjectOutput output, QueryRequest queryRequest) throws IOException {
output.writeUTF(queryRequest.getQueryString());
output.writeLong(queryRequest.getStartOffset() != null ? queryRequest.getStartOffset() : -1);
output.writeInt(queryRequest.getMaxResults() != null ? queryRequest.getMaxResults() : -1);
output.writeInt(queryRequest.hitCountAccuracy() != null ? queryRequest.hitCountAccuracy() : -1);
output.writeObject(queryRequest.getNamedParameters());
output.writeBoolean(queryRequest.isLocal());
}
@Override
@SuppressWarnings("unchecked")
public QueryRequest readObject(ObjectInput input) throws IOException, ClassNotFoundException {
QueryRequest queryRequest = new QueryRequest();
queryRequest.setQueryString(input.readUTF());
long startOffset = input.readLong();
queryRequest.setStartOffset(startOffset != -1 ? startOffset : null);
int maxResults = input.readInt();
queryRequest.setMaxResults(maxResults != -1 ? maxResults : null);
int hitCountAccuracy = input.readInt();
queryRequest.hitCountAccuracy(hitCountAccuracy != -1 ? hitCountAccuracy : null);
queryRequest.setNamedParameters((List<QueryRequest.NamedParameter>) input.readObject());
queryRequest.setLocal(input.readBoolean());
return queryRequest;
}
}
public static final class NamedParameterExternalizer implements Externalizer<QueryRequest.NamedParameter> {
@Override
public void writeObject(ObjectOutput output, QueryRequest.NamedParameter namedParameter) throws IOException {
output.writeUTF(namedParameter.getName());
output.writeObject(namedParameter.getValue());
}
@Override
public QueryRequest.NamedParameter readObject(ObjectInput input) throws IOException, ClassNotFoundException {
String name = input.readUTF();
Object value = input.readObject();
return new QueryRequest.NamedParameter(name, value);
}
}
public static final class QueryResponseExternalizer implements Externalizer<QueryResponse> {
@Override
public void writeObject(ObjectOutput output, QueryResponse queryResponse) throws IOException {
output.writeInt(queryResponse.getNumResults());
output.writeInt(queryResponse.getProjectionSize());
List<WrappedMessage> wrappedResults = queryResponse.getResults();
List<Object> results = new ArrayList<>(wrappedResults.size());
for (WrappedMessage o : wrappedResults) {
results.add(o.getValue());
}
output.writeObject(results);
output.writeInt(queryResponse.hitCount());
output.writeBoolean(queryResponse.hitCountExact());
}
@Override
@SuppressWarnings("unchecked")
public QueryResponse readObject(ObjectInput input) throws IOException, ClassNotFoundException {
QueryResponse queryResponse = new QueryResponse();
queryResponse.setNumResults(input.readInt());
queryResponse.setProjectionSize(input.readInt());
List<Object> results = (List<Object>) input.readObject();
List<WrappedMessage> wrappedResults = new ArrayList<>(results.size());
for (Object o : results) {
wrappedResults.add(new WrappedMessage(o));
}
queryResponse.setResults(wrappedResults);
queryResponse.hitCount(input.readInt());
queryResponse.hitCountExact(input.readBoolean());
return queryResponse;
}
}
}
| 4,218
| 40.362745
| 115
|
java
|
null |
infinispan-main/remote-query/remote-query-client/src/main/java/org/infinispan/query/remote/client/impl/QueryResponse.java
|
package org.infinispan.query.remote.client.impl;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.infinispan.commons.marshall.SerializeWith;
import org.infinispan.protostream.MessageMarshaller;
import org.infinispan.protostream.ProtobufUtil;
import org.infinispan.protostream.SerializationContext;
import org.infinispan.protostream.WrappedMessage;
/**
* @author anistor@redhat.com
* @since 6.0
*/
@SerializeWith(Externalizers.QueryResponseExternalizer.class)
public final class QueryResponse implements BaseQueryResponse {
private int numResults;
private int projectionSize;
private List<WrappedMessage> results;
private int hitCount;
private boolean hitCountExact;
public int getNumResults() {
return numResults;
}
public void setNumResults(int numResults) {
this.numResults = numResults;
}
public int getProjectionSize() {
return projectionSize;
}
public void setProjectionSize(int projectionSize) {
this.projectionSize = projectionSize;
}
public List<WrappedMessage> getResults() {
return results;
}
public void setResults(List<WrappedMessage> results) {
this.results = results;
}
@Override
public List<?> extractResults(SerializationContext serializationContext) throws IOException {
List<Object> unwrappedResults;
if (projectionSize > 0) {
unwrappedResults = new ArrayList<>(results.size() / projectionSize);
Iterator<WrappedMessage> it = results.iterator();
while (it.hasNext()) {
Object[] row = new Object[projectionSize];
for (int i = 0; i < row.length; i++) {
Object value = it.next().getValue();
if (value instanceof WrappedMessage) {
Object content = ((WrappedMessage) value).getValue();
if (content instanceof byte[]) {
value = ProtobufUtil.fromWrappedByteArray(serializationContext, (byte[]) content);
}
}
row[i] = value;
}
unwrappedResults.add(row);
}
} else {
unwrappedResults = new ArrayList<>(results.size());
for (WrappedMessage r : results) {
Object o = r.getValue();
if (serializationContext != null && o instanceof byte[]) {
o = ProtobufUtil.fromWrappedByteArray(serializationContext, (byte[]) o);
}
unwrappedResults.add(o);
}
}
return unwrappedResults;
}
@Override
public int hitCount() {
return hitCount;
}
public void hitCount(int hitCount) {
this.hitCount = hitCount;
}
@Override
public boolean hitCountExact() {
return hitCountExact;
}
public void hitCountExact(boolean hitCountExact) {
this.hitCountExact = hitCountExact;
}
static final class Marshaller implements MessageMarshaller<QueryResponse> {
@Override
public QueryResponse readFrom(ProtoStreamReader reader) throws IOException {
QueryResponse queryResponse = new QueryResponse();
queryResponse.setNumResults(reader.readInt("numResults"));
queryResponse.setProjectionSize(reader.readInt("projectionSize"));
queryResponse.setResults(reader.readCollection("results", new ArrayList<>(), WrappedMessage.class));
queryResponse.hitCount(reader.readInt("hitCount"));
queryResponse.hitCountExact(reader.readBoolean("hitCountExact"));
return queryResponse;
}
@Override
public void writeTo(ProtoStreamWriter writer, QueryResponse queryResponse) throws IOException {
writer.writeInt("numResults", queryResponse.numResults);
writer.writeInt("projectionSize", queryResponse.projectionSize);
writer.writeCollection("results", queryResponse.results, WrappedMessage.class);
writer.writeInt("hitCount", queryResponse.hitCount);
writer.writeBoolean("hitCountExact", queryResponse.hitCountExact);
}
@Override
public Class<QueryResponse> getJavaClass() {
return QueryResponse.class;
}
@Override
public String getTypeName() {
return "org.infinispan.query.remote.client.QueryResponse";
}
}
}
| 4,342
| 30.244604
| 109
|
java
|
null |
infinispan-main/remote-query/remote-query-client/src/main/java/org/infinispan/query/remote/client/impl/JsonClientQueryResponse.java
|
package org.infinispan.query.remote.client.impl;
import java.util.List;
import java.util.stream.Collectors;
import org.infinispan.commons.dataconversion.internal.Json;
import org.infinispan.protostream.SerializationContext;
/**
* @since 9.4
*/
public class JsonClientQueryResponse implements BaseQueryResponse<String> {
private static final String JSON_HITS = "hits";
private static final String JSON_HIT = "hit";
private static final String JSON_HIT_COUNT = "hit_count";
private static final String JSON_HIT_COUNT_EXACT = "hit_count_exact";
private final Json jsonObject;
public JsonClientQueryResponse(Json jsonObject) {
this.jsonObject = jsonObject;
}
@Override
public List<String> extractResults(SerializationContext serializationContext) {
return jsonObject.at(JSON_HITS).asJsonList().stream().map(j -> j.at(JSON_HIT).toString())
.collect(Collectors.toList());
}
@Override
public int hitCount() {
return jsonObject.at(JSON_HIT_COUNT).asInteger();
}
@Override
public boolean hitCountExact() {
return jsonObject.at(JSON_HIT_COUNT_EXACT).asBoolean();
}
}
| 1,152
| 27.121951
| 95
|
java
|
null |
infinispan-main/remote-query/remote-query-client/src/main/java/org/infinispan/query/remote/client/impl/BaseQueryResponse.java
|
package org.infinispan.query.remote.client.impl;
import java.io.IOException;
import java.util.List;
import org.infinispan.protostream.SerializationContext;
/**
* @since 9.4
*/
public interface BaseQueryResponse<T> {
List<T> extractResults(SerializationContext serializationContext) throws IOException;
int hitCount();
boolean hitCountExact();
}
| 363
| 17.2
| 88
|
java
|
null |
infinispan-main/remote-query/remote-query-client/src/main/java/org/infinispan/query/remote/client/impl/ContinuousQueryResult.java
|
package org.infinispan.query.remote.client.impl;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.infinispan.protostream.EnumMarshaller;
import org.infinispan.protostream.MessageMarshaller;
import org.infinispan.protostream.WrappedMessage;
/**
* @author anistor@redhat.com
* @since 8.0
*/
public final class ContinuousQueryResult {
public enum ResultType {
JOINING,
UPDATED,
LEAVING;
static final class Marshaller implements EnumMarshaller<ResultType> {
@Override
public ContinuousQueryResult.ResultType decode(int enumValue) {
switch (enumValue) {
case 0:
return ContinuousQueryResult.ResultType.LEAVING;
case 1:
return ContinuousQueryResult.ResultType.JOINING;
case 2:
return ContinuousQueryResult.ResultType.UPDATED;
}
return null;
}
@Override
public int encode(ContinuousQueryResult.ResultType resultType) throws IllegalArgumentException {
switch (resultType) {
case LEAVING:
return 0;
case JOINING:
return 1;
case UPDATED:
return 2;
default:
}
throw new IllegalArgumentException("Unexpected ResultType value : " + resultType);
}
@Override
public Class<ContinuousQueryResult.ResultType> getJavaClass() {
return ContinuousQueryResult.ResultType.class;
}
@Override
public String getTypeName() {
return "org.infinispan.query.remote.client.ContinuousQueryResult.ResultType";
}
}
}
private final ResultType resultType;
private final byte[] key;
private final byte[] value;
private final Object[] projection;
public ContinuousQueryResult(ResultType resultType, byte[] key, byte[] value, Object[] projection) {
this.resultType = resultType;
this.key = key;
this.value = value;
this.projection = projection;
}
public ResultType getResultType() {
return resultType;
}
public byte[] getKey() {
return key;
}
public byte[] getValue() {
return value;
}
public Object[] getProjection() {
return projection;
}
@Override
public String toString() {
return "ContinuousQueryResult{" +
"resultType=" + resultType +
", key=" + Arrays.toString(key) +
", value=" + Arrays.toString(value) +
", projection=" + Arrays.toString(projection) +
'}';
}
static final class Marshaller implements MessageMarshaller<ContinuousQueryResult> {
@Override
public ContinuousQueryResult readFrom(ProtoStreamReader reader) throws IOException {
ContinuousQueryResult.ResultType type = reader.readObject("resultType", ContinuousQueryResult.ResultType.class);
byte[] key = reader.readBytes("key");
byte[] value = reader.readBytes("value");
List<WrappedMessage> projection = reader.readCollection("projection", new ArrayList<>(), WrappedMessage.class);
Object[] p = null;
if (!projection.isEmpty()) {
p = new Object[projection.size()];
int j = 0;
for (WrappedMessage m : projection) {
p[j++] = m.getValue();
}
}
return new ContinuousQueryResult(type, key, value, p);
}
@Override
public void writeTo(ProtoStreamWriter writer, ContinuousQueryResult continuousQueryResult) throws IOException {
writer.writeObject("resultType", continuousQueryResult.getResultType(), ContinuousQueryResult.ResultType.class);
writer.writeBytes("key", continuousQueryResult.getKey());
if (continuousQueryResult.getProjection() == null) {
// skip marshalling the instance if there is a projection (they are mutually exclusive)
writer.writeBytes("value", continuousQueryResult.getValue());
} else {
WrappedMessage[] p = new WrappedMessage[continuousQueryResult.getProjection().length];
for (int i = 0; i < p.length; i++) {
p[i] = new WrappedMessage(continuousQueryResult.getProjection()[i]);
}
writer.writeArray("projection", p, WrappedMessage.class);
}
}
@Override
public Class<ContinuousQueryResult> getJavaClass() {
return ContinuousQueryResult.class;
}
@Override
public String getTypeName() {
return "org.infinispan.query.remote.client.ContinuousQueryResult";
}
}
}
| 4,777
| 30.642384
| 121
|
java
|
null |
infinispan-main/remote-query/remote-query-client/src/main/java/org/infinispan/query/remote/client/impl/QueryRequest.java
|
package org.infinispan.query.remote.client.impl;
import static java.util.stream.Collectors.toList;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.infinispan.commons.dataconversion.internal.Json;
import org.infinispan.commons.dataconversion.internal.JsonSerialization;
import org.infinispan.commons.marshall.SerializeWith;
import org.infinispan.protostream.MessageMarshaller;
import org.infinispan.protostream.WrappedMessage;
/**
* @author anistor@redhat.com
* @since 6.0
*/
@SerializeWith(Externalizers.QueryRequestExternalizer.class)
public final class QueryRequest implements JsonSerialization {
public static final String QUERY_STRING_FIELD = "queryString";
public static final String START_OFFSET_FIELD = "startOffset";
public static final String MAX_RESULTS_FIELD = "maxResults";
public static final String HIT_COUNT_ACCURACY = "hitCountAccuracy";
public static final String NAMED_PARAMETERS_FIELD = "namedParameters";
public static final String LOCAL_FIELD = "local";
private String queryString;
private List<NamedParameter> namedParameters;
private Long startOffset;
private Integer maxResults;
private Integer hitCountAccuracy;
private boolean local;
public String getQueryString() {
return queryString;
}
public void setQueryString(String queryString) {
this.queryString = queryString;
}
public Long getStartOffset() {
return startOffset == null ? Long.valueOf(-1) : startOffset;
}
public void setStartOffset(Long startOffset) {
this.startOffset = startOffset;
}
public Integer getMaxResults() {
return maxResults == null ? Integer.valueOf(-1) : maxResults;
}
public void setMaxResults(Integer maxResults) {
this.maxResults = maxResults;
}
public Integer hitCountAccuracy() {
return hitCountAccuracy == null ? Integer.valueOf(-1) : hitCountAccuracy;
}
public void hitCountAccuracy(Integer hitCountAccuracy) {
this.hitCountAccuracy = hitCountAccuracy;
}
public List<NamedParameter> getNamedParameters() {
return namedParameters;
}
public boolean isLocal() {
return local;
}
public void setLocal(boolean local) {
this.local = local;
}
public void setNamedParameters(List<NamedParameter> namedParameters) {
this.namedParameters = namedParameters;
}
public Map<String, Object> getNamedParametersMap() {
if (namedParameters == null || namedParameters.isEmpty()) {
return null;
}
Map<String, Object> params = new HashMap<>(namedParameters.size());
for (NamedParameter p : namedParameters) {
params.put(p.getName(), p.getValue());
}
return params;
}
public static QueryRequest fromJson(Json jsonRequest) {
String queryString = jsonRequest.at(QUERY_STRING_FIELD).asString();
Json offsetValue = jsonRequest.at(START_OFFSET_FIELD);
Json maxResults = jsonRequest.at(MAX_RESULTS_FIELD);
Json hitCountAccuracy = jsonRequest.at(HIT_COUNT_ACCURACY);
Json named = jsonRequest.at(NAMED_PARAMETERS_FIELD);
List<NamedParameter> params = named.isArray() ? named.asJsonList().stream()
.map(NamedParameter::fromJson).collect(toList()) : Collections.emptyList();
QueryRequest queryRequest = new QueryRequest();
queryRequest.setQueryString(queryString);
if (!offsetValue.isNull()) queryRequest.setStartOffset(offsetValue.asLong());
if (!maxResults.isNull()) queryRequest.setMaxResults(maxResults.asInteger());
if (!hitCountAccuracy.isNull()) queryRequest.hitCountAccuracy(hitCountAccuracy.asInteger());
if (!params.isEmpty()) queryRequest.setNamedParameters(params);
return queryRequest;
}
@Override
public Json toJson() {
return Json.object()
.set(QUERY_STRING_FIELD, queryString)
.set(START_OFFSET_FIELD, startOffset)
.set(MAX_RESULTS_FIELD, maxResults)
.set(HIT_COUNT_ACCURACY, hitCountAccuracy)
.set(NAMED_PARAMETERS_FIELD, Json.make(getNamedParameters()))
.set(LOCAL_FIELD, Json.factory().bool(local));
}
static final class Marshaller implements MessageMarshaller<QueryRequest> {
@Override
public QueryRequest readFrom(ProtoStreamReader reader) throws IOException {
QueryRequest queryRequest = new QueryRequest();
queryRequest.setQueryString(reader.readString(QUERY_STRING_FIELD));
queryRequest.setStartOffset(reader.readLong(START_OFFSET_FIELD));
queryRequest.setMaxResults(reader.readInt(MAX_RESULTS_FIELD));
queryRequest.hitCountAccuracy(reader.readInt(HIT_COUNT_ACCURACY));
queryRequest.setNamedParameters(reader.readCollection(NAMED_PARAMETERS_FIELD, new ArrayList<>(), NamedParameter.class));
Boolean localField = reader.readBoolean(LOCAL_FIELD);
if (localField != null) queryRequest.setLocal(localField);
return queryRequest;
}
@Override
public void writeTo(ProtoStreamWriter writer, QueryRequest queryRequest) throws IOException {
writer.writeString(QUERY_STRING_FIELD, queryRequest.getQueryString());
writer.writeLong(START_OFFSET_FIELD, queryRequest.getStartOffset());
writer.writeInt(MAX_RESULTS_FIELD, queryRequest.getMaxResults());
writer.writeInt(HIT_COUNT_ACCURACY, queryRequest.hitCountAccuracy());
writer.writeCollection(NAMED_PARAMETERS_FIELD, queryRequest.getNamedParameters(), NamedParameter.class);
writer.writeBoolean(LOCAL_FIELD, queryRequest.isLocal());
}
@Override
public Class<QueryRequest> getJavaClass() {
return QueryRequest.class;
}
@Override
public String getTypeName() {
return "org.infinispan.query.remote.client.QueryRequest";
}
}
@SerializeWith(Externalizers.NamedParameterExternalizer.class)
public static final class NamedParameter implements JsonSerialization {
public static final String NAME_FIELD = "name";
public static final String VALUE_FIELD = "value";
private final String name;
private final Object value;
public NamedParameter(String name, Object value) {
if (name == null) {
throw new IllegalArgumentException("name cannot be null");
}
if (value == null) {
throw new IllegalArgumentException("value cannot be null");
}
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public Object getValue() {
return value;
}
@Override
public Json toJson() {
return Json.object(NAME_FIELD, name).set(VALUE_FIELD, value);
}
public static NamedParameter fromJson(Json source) {
String name = source.at(NAME_FIELD).asString();
Object value = source.at(VALUE_FIELD).getValue();
return new NamedParameter(name, value);
}
static final class Marshaller implements MessageMarshaller<NamedParameter> {
@Override
public NamedParameter readFrom(ProtoStreamReader reader) throws IOException {
String name = reader.readString("name");
WrappedMessage value = reader.readObject("value", WrappedMessage.class);
return new NamedParameter(name, value.getValue());
}
@Override
public void writeTo(ProtoStreamWriter writer, NamedParameter namedParameter) throws IOException {
writer.writeString("name", namedParameter.getName());
writer.writeObject("value", new WrappedMessage(namedParameter.getValue()), WrappedMessage.class);
}
@Override
public Class<NamedParameter> getJavaClass() {
return NamedParameter.class;
}
@Override
public String getTypeName() {
return "org.infinispan.query.remote.client.QueryRequest.NamedParameter";
}
}
}
}
| 8,132
| 33.75641
| 129
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/AbstractNonFunctionalTest.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform;
import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform;
import org.hibernate.resource.transaction.spi.TransactionStatus;
import org.hibernate.testing.junit4.CustomParameterized;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.hibernate.cache.commons.util.Caches;
import org.infinispan.test.hibernate.cache.commons.util.BatchModeJtaPlatform;
import org.infinispan.test.hibernate.cache.commons.util.CacheTestSupport;
import org.infinispan.test.hibernate.cache.commons.util.CacheTestUtil;
import org.infinispan.test.hibernate.cache.commons.util.InfinispanTestingSetup;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactory;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactoryProvider;
import org.infinispan.test.hibernate.cache.commons.util.TestSessionAccess;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import jakarta.transaction.TransactionManager;
/**
* Base class for all non-functional tests of Infinispan integration.
*
* @author Galder Zamarreño
* @since 3.5
*/
@RunWith(CustomParameterized.class)
public abstract class AbstractNonFunctionalTest extends org.hibernate.testing.junit4.BaseUnitTestCase {
@ClassRule
public static final InfinispanTestingSetup infinispanTestIdentifier = new InfinispanTestingSetup();
protected static final TestSessionAccess TEST_SESSION_ACCESS = TestSessionAccess.findTestSessionAccess();
@Parameterized.Parameter(0)
public String mode;
@Parameterized.Parameter(1)
public Class<? extends JtaPlatform> jtaPlatform;
@Parameterized.Parameter(2)
public CacheMode cacheMode;
@Parameterized.Parameter(3)
public AccessType accessType;
public static final String REGION_PREFIX = "test";
private static final String PREFER_IPV4STACK = "java.net.preferIPv4Stack";
private String preferIPv4Stack;
private static final String JGROUPS_CFG_FILE = "hibernate.cache.infinispan.jgroups_cfg";
private String jgroupsCfgFile;
private CacheTestSupport testSupport = new CacheTestSupport();
@Parameterized.Parameters(name = "{0}, {2}, {3}")
public List<Object[]> getParameters() {
List<Object[]> parameters = new ArrayList<>(Arrays.asList(
new Object[]{"JTA", BatchModeJtaPlatform.class, CacheMode.INVALIDATION_SYNC, AccessType.TRANSACTIONAL},
new Object[]{"JTA", BatchModeJtaPlatform.class, CacheMode.INVALIDATION_SYNC, AccessType.READ_WRITE},
new Object[]{"JTA", BatchModeJtaPlatform.class, CacheMode.INVALIDATION_SYNC, AccessType.READ_ONLY},
new Object[]{"JTA", BatchModeJtaPlatform.class, CacheMode.DIST_SYNC, AccessType.READ_WRITE},
new Object[]{"JTA", BatchModeJtaPlatform.class, CacheMode.DIST_SYNC, AccessType.READ_ONLY},
new Object[]{"JTA", BatchModeJtaPlatform.class, CacheMode.DIST_SYNC, AccessType.NONSTRICT_READ_WRITE},
new Object[]{"JTA", BatchModeJtaPlatform.class, CacheMode.REPL_SYNC, AccessType.READ_WRITE},
new Object[]{"JTA", BatchModeJtaPlatform.class, CacheMode.REPL_SYNC, AccessType.READ_ONLY},
new Object[]{"JTA", BatchModeJtaPlatform.class, CacheMode.REPL_SYNC, AccessType.NONSTRICT_READ_WRITE},
new Object[]{"non-JTA", NoJtaPlatform.class, CacheMode.INVALIDATION_SYNC, AccessType.READ_WRITE},
new Object[]{"non-JTA", NoJtaPlatform.class, CacheMode.INVALIDATION_SYNC, AccessType.READ_ONLY},
new Object[]{"non-JTA", NoJtaPlatform.class, CacheMode.DIST_SYNC, AccessType.READ_WRITE},
new Object[]{"non-JTA", NoJtaPlatform.class, CacheMode.DIST_SYNC, AccessType.READ_ONLY},
new Object[]{"non-JTA", NoJtaPlatform.class, CacheMode.DIST_SYNC, AccessType.NONSTRICT_READ_WRITE},
new Object[]{"non-JTA", NoJtaPlatform.class, CacheMode.REPL_SYNC, AccessType.READ_WRITE},
new Object[]{"non-JTA", NoJtaPlatform.class, CacheMode.REPL_SYNC, AccessType.READ_ONLY},
new Object[]{"non-JTA", NoJtaPlatform.class, CacheMode.REPL_SYNC, AccessType.NONSTRICT_READ_WRITE}
));
if (canUseLocalMode()) {
parameters.addAll(Arrays.asList(
new Object[]{"JTA", BatchModeJtaPlatform.class, CacheMode.LOCAL, AccessType.TRANSACTIONAL},
new Object[]{"JTA", BatchModeJtaPlatform.class, CacheMode.LOCAL, AccessType.READ_WRITE},
new Object[]{"JTA", BatchModeJtaPlatform.class, CacheMode.LOCAL, AccessType.READ_ONLY},
new Object[]{"JTA", BatchModeJtaPlatform.class, CacheMode.LOCAL, AccessType.NONSTRICT_READ_WRITE},
new Object[]{"non-JTA", NoJtaPlatform.class, CacheMode.LOCAL, AccessType.READ_WRITE},
new Object[]{"non-JTA", NoJtaPlatform.class, CacheMode.LOCAL, AccessType.READ_ONLY},
new Object[]{"non-JTA", NoJtaPlatform.class, CacheMode.LOCAL, AccessType.NONSTRICT_READ_WRITE}
));
}
return parameters;
}
@Before
public void prepareCacheSupport() throws Exception {
infinispanTestIdentifier.joinContext();
preferIPv4Stack = System.getProperty(PREFER_IPV4STACK);
System.setProperty(PREFER_IPV4STACK, "true");
jgroupsCfgFile = System.getProperty(JGROUPS_CFG_FILE);
System.setProperty(JGROUPS_CFG_FILE, "2lc-test-tcp.xml");
testSupport.setUp();
}
@After
public void releaseCachSupport() throws Exception {
testSupport.tearDown();
if (preferIPv4Stack == null) {
System.clearProperty(PREFER_IPV4STACK);
} else {
System.setProperty(PREFER_IPV4STACK, preferIPv4Stack);
}
if (jgroupsCfgFile == null)
System.clearProperty(JGROUPS_CFG_FILE);
else
System.setProperty(JGROUPS_CFG_FILE, jgroupsCfgFile);
}
protected boolean canUseLocalMode() {
return true;
}
protected <T> T withTx(NodeEnvironment environment, Object session, Callable<T> callable) throws Exception {
TransactionManager tm = environment.getServiceRegistry().getService(JtaPlatform.class).retrieveTransactionManager();
if (tm != null) {
return Caches.withinTx(tm, callable);
} else {
Transaction transaction = TEST_SESSION_ACCESS.beginTransaction(session);
boolean rollingBack = false;
try {
T retval = callable.call();
if (transaction.getStatus() == TransactionStatus.ACTIVE) {
transaction.commit();
} else {
rollingBack = true;
transaction.rollback();
}
return retval;
} catch (Exception e) {
if (!rollingBack) {
try {
transaction.rollback();
} catch (Exception suppressed) {
e.addSuppressed(suppressed);
}
}
throw e;
}
}
}
protected CacheTestSupport getCacheTestSupport() {
return testSupport;
}
protected StandardServiceRegistryBuilder createStandardServiceRegistryBuilder() {
final StandardServiceRegistryBuilder ssrb = CacheTestUtil.buildBaselineStandardServiceRegistryBuilder(
REGION_PREFIX, true, false, jtaPlatform);
ssrb.applySetting(TestRegionFactory.TRANSACTIONAL, TestRegionFactoryProvider.load().supportTransactionalCaches() && accessType == AccessType.TRANSACTIONAL);
ssrb.applySetting(TestRegionFactory.CACHE_MODE, cacheMode);
return ssrb;
}
}
| 7,572
| 41.072222
| 158
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/AbstractGeneralDataRegionTest.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.stream.Collectors;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cache.spi.QueryResultsRegion;
import org.hibernate.cache.spi.RegionFactory;
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform;
import org.infinispan.AdvancedCache;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.hibernate.cache.commons.InfinispanBaseRegion;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.hibernate.cache.commons.util.BatchModeJtaPlatform;
import org.infinispan.test.hibernate.cache.commons.util.CacheTestUtil;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactory;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactoryProvider;
import org.infinispan.test.hibernate.cache.commons.util.TestSessionAccess;
import org.infinispan.test.hibernate.cache.commons.util.TestSessionAccess.TestRegion;
/**
* Base class for tests of QueryResultsRegion and TimestampsRegion.
*
* @author Galder Zamarreño
* @since 3.5
*/
public abstract class AbstractGeneralDataRegionTest extends AbstractRegionImplTest {
protected static final String KEY = "Key";
protected static final String VALUE1 = "value1";
protected static final String VALUE2 = "value2";
protected static final String VALUE3 = "value3";
protected static final TestSessionAccess TEST_SESSION_ACCESS = TestSessionAccess.findTestSessionAccess();
@Override
public List<Object[]> getParameters() {
// the actual cache mode and access type is irrelevant for the general data regions
return Arrays.asList(
new Object[]{"JTA", BatchModeJtaPlatform.class, CacheMode.INVALIDATION_SYNC, AccessType.TRANSACTIONAL},
new Object[]{"non-JTA", NoJtaPlatform.class, CacheMode.INVALIDATION_SYNC, AccessType.READ_WRITE}
);
}
protected interface SFRConsumer {
void accept(List<SessionFactory> sessionFactories, List<InfinispanBaseRegion> regions) throws Exception;
}
protected void withSessionFactoriesAndRegions(int num, SFRConsumer consumer) throws Exception {
StandardServiceRegistryBuilder ssrb = createStandardServiceRegistryBuilder()
.applySetting(AvailableSettings.CACHE_REGION_FACTORY, TestRegionFactoryProvider.load().getRegionFactoryClass().getName());
Properties properties = CacheTestUtil.toProperties( ssrb.getSettings() );
List<StandardServiceRegistry> registries = new ArrayList<>();
List<SessionFactory> sessionFactories = new ArrayList<>();
List<InfinispanBaseRegion> regions = new ArrayList<>();
for (int i = 0; i < num; ++i) {
StandardServiceRegistry registry = ssrb.build();
registries.add(registry);
SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
sessionFactories.add(sessionFactory);
TestRegionFactory regionFactory = TestRegionFactoryProvider.load().wrap(registry.getService(RegionFactory.class));
InfinispanBaseRegion region = createRegion(regionFactory, REGION_PREFIX + "/who-cares");
regions.add(region);
}
waitForClusterToForm(regions);
try {
consumer.accept(sessionFactories, regions);
} finally {
for (SessionFactory sessionFactory : sessionFactories) {
sessionFactory.close();
}
for (StandardServiceRegistry registry : registries) {
StandardServiceRegistryBuilder.destroy( registry );
}
}
}
private void waitForClusterToForm(List<InfinispanBaseRegion> regions) {
List<AdvancedCache> caches = regions.stream()
.map(InfinispanBaseRegion::getCache)
.collect(Collectors.toList());
TestingUtil.blockUntilViewsReceived(20000, caches);
TestingUtil.waitForNoRebalance(caches);
}
/**
* Test method for {@link QueryResultsRegion#evictAll()}.
* <p/>
* FIXME add testing of the "immediately without regard for transaction isolation" bit in the
* CollectionRegionAccessStrategy API.
*/
public void testEvictAll() throws Exception {
withSessionFactoriesAndRegions(2, (sessionFactories, regions) -> {
InfinispanBaseRegion localRegion = regions.get(0);
TestRegion testLocalRegion = TEST_SESSION_ACCESS.fromRegion(localRegion);
InfinispanBaseRegion remoteRegion = regions.get(1);
TestRegion testRemoteRegion = TEST_SESSION_ACCESS.fromRegion(remoteRegion);
AdvancedCache localCache = localRegion.getCache();
AdvancedCache remoteCache = remoteRegion.getCache();
Object localSession = sessionFactories.get(0).openSession();
Object remoteSession = sessionFactories.get(1).openSession();
try {
Set localKeys = localCache.keySet();
assertEquals( "No valid children in " + localKeys, 0, localKeys.size() );
Set remoteKeys = remoteCache.keySet();
assertEquals( "No valid children in " + remoteKeys, 0, remoteKeys.size() );
assertNull( "local is clean", testLocalRegion.get(null, KEY ) );
assertNull( "remote is clean", testRemoteRegion.get(null, KEY ) );
testLocalRegion.put(localSession, KEY, VALUE1);
assertEquals( VALUE1, testLocalRegion.get(null, KEY ) );
testRemoteRegion.put(remoteSession, KEY, VALUE1);
assertEquals( VALUE1, testRemoteRegion.get(null, KEY ) );
testLocalRegion.evictAll();
// This should re-establish the region root node in the optimistic case
assertNull( testLocalRegion.get(null, KEY ) );
localKeys = localCache.keySet();
assertEquals( "No valid children in " + localKeys, 0, localKeys.size() );
// Re-establishing the region root on the local node doesn't
// propagate it to other nodes. Do a get on the remote node to re-establish
// This only adds a node in the case of optimistic locking
assertEquals( null, testRemoteRegion.get(null, KEY ) );
remoteKeys = remoteCache.keySet();
assertEquals( "No valid children in " + remoteKeys, 0, remoteKeys.size() );
assertEquals( "local is clean", null, testLocalRegion.get(null, KEY ) );
assertEquals( "remote is clean", null, testRemoteRegion.get(null, KEY ) );
} finally {
( (Session) localSession ).close();
( (Session) remoteSession ).close();
}
});
}
}
| 6,882
| 40.463855
| 126
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.