repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableRepositoryFactoryConfiguration.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableRepositoryFactoryConfiguration.java | package com.mmnaseri.utils.spring.data.proxy.impl;
import com.mmnaseri.utils.spring.data.domain.KeyGenerator;
import com.mmnaseri.utils.spring.data.domain.RepositoryMetadataResolver;
import com.mmnaseri.utils.spring.data.domain.impl.MethodQueryDescriptionExtractor;
import com.mmnaseri.utils.spring.data.proxy.RepositoryFactoryConfiguration;
import com.mmnaseri.utils.spring.data.proxy.ResultAdapterContext;
import com.mmnaseri.utils.spring.data.proxy.TypeMappingContext;
import com.mmnaseri.utils.spring.data.query.DataFunctionRegistry;
import com.mmnaseri.utils.spring.data.store.DataStoreEventListenerContext;
import com.mmnaseri.utils.spring.data.store.DataStoreRegistry;
/**
* This class is an immutable repository factory configuration insofar as the configuration itself
* is considered. The properties themselves won't be protected and are open to external change.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/12/16, 1:49 PM)
*/
@SuppressWarnings("WeakerAccess")
public class ImmutableRepositoryFactoryConfiguration implements RepositoryFactoryConfiguration {
private final RepositoryMetadataResolver metadataResolver;
private final MethodQueryDescriptionExtractor queryDescriptionExtractor;
private final DataFunctionRegistry functionRegistry;
private final DataStoreRegistry dataStoreRegistry;
private final ResultAdapterContext resultAdapterContext;
private final TypeMappingContext typeMappingContext;
private final DataStoreEventListenerContext eventListenerContext;
private final NonDataOperationInvocationHandler operationInvocationHandler;
private final KeyGenerator<?> keyGenerator;
public ImmutableRepositoryFactoryConfiguration(RepositoryFactoryConfiguration configuration) {
this(
configuration.getRepositoryMetadataResolver(),
configuration.getDescriptionExtractor(),
configuration.getFunctionRegistry(),
configuration.getDataStoreRegistry(),
configuration.getResultAdapterContext(),
configuration.getTypeMappingContext(),
configuration.getEventListenerContext(),
configuration.getOperationInvocationHandler(),
configuration.getDefaultKeyGenerator());
}
public ImmutableRepositoryFactoryConfiguration(
RepositoryMetadataResolver metadataResolver,
MethodQueryDescriptionExtractor queryDescriptionExtractor,
DataFunctionRegistry functionRegistry,
DataStoreRegistry dataStoreRegistry,
ResultAdapterContext resultAdapterContext,
TypeMappingContext typeMappingContext,
DataStoreEventListenerContext eventListenerContext,
NonDataOperationInvocationHandler operationInvocationHandler,
KeyGenerator<?> keyGenerator) {
this.metadataResolver = metadataResolver;
this.queryDescriptionExtractor = queryDescriptionExtractor;
this.functionRegistry = functionRegistry;
this.dataStoreRegistry = dataStoreRegistry;
this.resultAdapterContext = resultAdapterContext;
this.typeMappingContext = typeMappingContext;
this.eventListenerContext = eventListenerContext;
this.operationInvocationHandler = operationInvocationHandler;
this.keyGenerator = keyGenerator;
}
@Override
public RepositoryMetadataResolver getRepositoryMetadataResolver() {
return metadataResolver;
}
@Override
public MethodQueryDescriptionExtractor getDescriptionExtractor() {
return queryDescriptionExtractor;
}
@Override
public DataFunctionRegistry getFunctionRegistry() {
return functionRegistry;
}
@Override
public DataStoreRegistry getDataStoreRegistry() {
return dataStoreRegistry;
}
@Override
public ResultAdapterContext getResultAdapterContext() {
return resultAdapterContext;
}
@Override
public TypeMappingContext getTypeMappingContext() {
return typeMappingContext;
}
@Override
public DataStoreEventListenerContext getEventListenerContext() {
return eventListenerContext;
}
@Override
public NonDataOperationInvocationHandler getOperationInvocationHandler() {
return operationInvocationHandler;
}
@Override
public KeyGenerator<?> getDefaultKeyGenerator() {
return keyGenerator;
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultRepositoryFactory.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultRepositoryFactory.java | package com.mmnaseri.utils.spring.data.proxy.impl;
import com.mmnaseri.utils.spring.data.domain.DataStoreAware;
import com.mmnaseri.utils.spring.data.domain.KeyGenerator;
import com.mmnaseri.utils.spring.data.domain.KeyGeneratorAware;
import com.mmnaseri.utils.spring.data.domain.RepositoryAware;
import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata;
import com.mmnaseri.utils.spring.data.domain.RepositoryMetadataAware;
import com.mmnaseri.utils.spring.data.domain.RepositoryMetadataResolver;
import com.mmnaseri.utils.spring.data.domain.impl.MethodQueryDescriptionExtractor;
import com.mmnaseri.utils.spring.data.domain.impl.key.NoOpKeyGenerator;
import com.mmnaseri.utils.spring.data.proxy.DataOperationResolver;
import com.mmnaseri.utils.spring.data.proxy.InvocationMapping;
import com.mmnaseri.utils.spring.data.proxy.RepositoryConfiguration;
import com.mmnaseri.utils.spring.data.proxy.RepositoryConfigurationAware;
import com.mmnaseri.utils.spring.data.proxy.RepositoryFactory;
import com.mmnaseri.utils.spring.data.proxy.RepositoryFactoryAware;
import com.mmnaseri.utils.spring.data.proxy.RepositoryFactoryConfiguration;
import com.mmnaseri.utils.spring.data.proxy.RepositoryFactoryConfigurationAware;
import com.mmnaseri.utils.spring.data.proxy.ResultAdapterContext;
import com.mmnaseri.utils.spring.data.proxy.TypeMapping;
import com.mmnaseri.utils.spring.data.proxy.TypeMappingContext;
import com.mmnaseri.utils.spring.data.proxy.impl.resolvers.DefaultDataOperationResolver;
import com.mmnaseri.utils.spring.data.query.DataFunctionRegistry;
import com.mmnaseri.utils.spring.data.store.DataStore;
import com.mmnaseri.utils.spring.data.store.DataStoreOperation;
import com.mmnaseri.utils.spring.data.store.DataStoreRegistry;
import com.mmnaseri.utils.spring.data.store.impl.DefaultDataStoreEventListenerContext;
import com.mmnaseri.utils.spring.data.store.impl.EventPublishingDataStore;
import com.mmnaseri.utils.spring.data.store.impl.MemoryDataStore;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* This class is the entry point to this framework as a whole. Using this class, you can mock a
* repository interface by passing the proper set of configurations and parameters.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/29/15)
*/
public class DefaultRepositoryFactory implements RepositoryFactory {
private static final Log log = LogFactory.getLog(DefaultRepositoryFactory.class);
private final RepositoryMetadataResolver repositoryMetadataResolver;
private final Map<Class<?>, RepositoryMetadata> metadataMap = new ConcurrentHashMap<>();
private final MethodQueryDescriptionExtractor descriptionExtractor;
private final DataFunctionRegistry functionRegistry;
private final DataStoreRegistry dataStoreRegistry;
private final ResultAdapterContext adapterContext;
private final TypeMappingContext typeMappingContext;
private final RepositoryFactoryConfiguration configuration;
private final NonDataOperationInvocationHandler operationInvocationHandler;
public DefaultRepositoryFactory(RepositoryFactoryConfiguration configuration) {
this.configuration = configuration;
this.repositoryMetadataResolver = configuration.getRepositoryMetadataResolver();
this.descriptionExtractor = configuration.getDescriptionExtractor();
this.functionRegistry = configuration.getFunctionRegistry();
this.dataStoreRegistry = configuration.getDataStoreRegistry();
this.adapterContext = configuration.getResultAdapterContext();
this.typeMappingContext = configuration.getTypeMappingContext();
this.operationInvocationHandler = configuration.getOperationInvocationHandler();
}
@Override
public <E> E getInstance(
KeyGenerator<?> keyGenerator, Class<E> repositoryInterface, Class... implementations) {
final KeyGenerator<?> actualKeyGenerator;
if (keyGenerator == null) {
if (configuration.getDefaultKeyGenerator() != null) {
// if no key generator is passed and there is a default key generator specified, we fall
// back to that
actualKeyGenerator = configuration.getDefaultKeyGenerator();
} else {
// otherwise, let's assume that not key generation is required
actualKeyGenerator = new NoOpKeyGenerator<>();
}
} else {
actualKeyGenerator = keyGenerator;
}
log.info(
"We are going to create a proxy instance of type "
+ repositoryInterface
+ " using key generator "
+ actualKeyGenerator
+ " and binding the implementations to "
+ Arrays.toString(implementations));
// figure out the repository metadata
log.info("Resolving repository metadata for " + repositoryInterface);
final RepositoryMetadata metadata = getRepositoryMetadata(repositoryInterface);
// get the underlying data store
log.info("Resolving the data store for " + repositoryInterface);
final DataStore<Object, ?> dataStore = getDataStore(metadata);
// figure out type mappings
log.info(
"Trying to find all the proper type mappings for entity repository " + repositoryInterface);
final List<TypeMapping<?>> typeMappings =
getTypeMappings(metadata, dataStore, actualKeyGenerator, implementations);
// set up the data operation resolver
final DataOperationResolver operationResolver =
new DefaultDataOperationResolver(
typeMappings, descriptionExtractor, metadata, functionRegistry, configuration);
// get all of this repository's methods
final Method[] methods = repositoryInterface.getMethods();
// get mappings for the repository methods
log.info(
"Trying to find all the invocation mappings for methods declared on "
+ repositoryInterface);
final List<InvocationMapping<?, ?>> invocationMappings =
getInvocationMappings(operationResolver, methods);
// extract the bound implementation types
final List<Class<?>> boundImplementations = new LinkedList<>();
for (TypeMapping<?> mapping : typeMappings) {
boundImplementations.add(mapping.getType());
}
// set up the repository configuration
final RepositoryConfiguration repositoryConfiguration =
new ImmutableRepositoryConfiguration(metadata, actualKeyGenerator, boundImplementations);
// create the interceptor
//noinspection unchecked
final InvocationHandler interceptor =
new DataOperationInvocationHandler(
repositoryConfiguration,
invocationMappings,
dataStore,
adapterContext,
operationInvocationHandler);
// create a proxy for the repository
log.info("Instantiating the proxy using the provided configuration");
final Object instance =
Proxy.newProxyInstance(
getClass().getClassLoader(), new Class[] {repositoryInterface}, interceptor);
// for each type mapping, inject proper dependencies
for (TypeMapping<?> typeMapping : typeMappings) {
log.info(
"Injecting all the required dependencies into the repository mapping implementations");
if (typeMapping.getInstance() instanceof RepositoryAware<?>) {
//noinspection unchecked
((RepositoryAware) typeMapping.getInstance()).setRepository(instance);
}
if (typeMapping.getInstance() instanceof RepositoryConfigurationAware) {
((RepositoryConfigurationAware) typeMapping.getInstance())
.setRepositoryConfiguration(repositoryConfiguration);
}
if (typeMapping.getInstance() instanceof RepositoryFactoryAware) {
((RepositoryFactoryAware) typeMapping.getInstance()).setRepositoryFactory(this);
}
}
// return the repository instance
return repositoryInterface.cast(instance);
}
@Override
public RepositoryFactoryConfiguration getConfiguration() {
return configuration;
}
/**
* Given a repository metadata, it will find out all the proper type mappings bound as
* implementations to the repository. These will come from the {@link TypeMappingContext},
* overridden by the implementations provided by the user for this specific case.
*
* <p>If the mapped concrete class needs to know anything from the current mocking context, it can
* implement one of the various {@link org.springframework.beans.factory.Aware aware} interfaces
* to be given the proper piece of contextual information.
*
* @param metadata the repository metadata
* @param dataStore the data store
* @param keyGenerator the key generator
* @param implementations the implementations specified by the user
* @return the resolved list of type mappings
*/
private List<TypeMapping<?>> getTypeMappings(
RepositoryMetadata metadata,
DataStore<Object, ?> dataStore,
KeyGenerator<?> keyGenerator,
Class[] implementations) {
final TypeMappingContext localContext = new DefaultTypeMappingContext(typeMappingContext);
for (Class implementation : implementations) {
localContext.register(metadata.getRepositoryInterface(), implementation);
}
final List<TypeMapping<?>> typeMappings =
new LinkedList<>(localContext.getMappings(metadata.getRepositoryInterface()));
for (TypeMapping<?> mapping : typeMappings) {
if (mapping.getInstance() instanceof DataStoreAware<?, ?>) {
DataStoreAware instance = (DataStoreAware<?, ?>) mapping.getInstance();
instance.setDataStore(dataStore);
}
if (mapping.getInstance() instanceof RepositoryMetadataAware) {
RepositoryMetadataAware instance = (RepositoryMetadataAware) mapping.getInstance();
instance.setRepositoryMetadata(metadata);
}
if (mapping.getInstance() instanceof KeyGeneratorAware) {
KeyGeneratorAware instance = (KeyGeneratorAware) mapping.getInstance();
//noinspection unchecked
instance.setKeyGenerator(keyGenerator);
}
if (mapping.getInstance() instanceof RepositoryFactoryConfigurationAware) {
RepositoryFactoryConfigurationAware instance =
(RepositoryFactoryConfigurationAware) mapping.getInstance();
instance.setRepositoryFactoryConfiguration(configuration);
}
}
return typeMappings;
}
/**
* Given a repository interface, it will resolve the metadata for that interface.
*
* @param repositoryInterface the interface
* @param <E> the type of the interface
* @return the repository metadata associated with the interface
*/
private <E> RepositoryMetadata getRepositoryMetadata(Class<E> repositoryInterface) {
final RepositoryMetadata metadata;
if (metadataMap.containsKey(repositoryInterface)) {
metadata = metadataMap.get(repositoryInterface);
} else {
metadata = repositoryMetadataResolver.resolve(repositoryInterface);
metadataMap.put(repositoryInterface, metadata);
}
return metadata;
}
/**
* Given a repository metadata, it will return the data store instance associated with the entity
* type for that repository.
*
* <p>If the data store is not an instance of {@link EventPublishingDataStore} it will wrap it in
* one, thus enabling event processing for this repository.
*
* <p>It will also register the data store instance to let the user access the data store, as well
* as cache it for future use.
*
* @param metadata the metadata
* @return the data store
*/
private DataStore<Object, ?> getDataStore(RepositoryMetadata metadata) {
DataStore<Object, ?> dataStore;
if (dataStoreRegistry.has(metadata.getEntityType())) {
dataStore = dataStoreRegistry.getDataStore(metadata.getEntityType());
} else {
//noinspection unchecked
dataStore = new MemoryDataStore<>((Class<Object>) metadata.getEntityType());
}
if (!(dataStore instanceof EventPublishingDataStore)) {
dataStore =
new EventPublishingDataStore<>(
dataStore,
metadata,
new DefaultDataStoreEventListenerContext(configuration.getEventListenerContext()));
}
dataStoreRegistry.register(dataStore);
return dataStore;
}
/**
* Given a set of methods, it will rely on a {@link DataOperationResolver} to find the mappings
* for each of the methods.
*
* @param operationResolver the resolver to use
* @param methods the array of methods
* @return resolved invocations
*/
private List<InvocationMapping<?, ?>> getInvocationMappings(
DataOperationResolver operationResolver, Method[] methods) {
final List<InvocationMapping<?, ?>> invocationMappings = new LinkedList<>();
for (Method method : methods) {
if (method.isDefault()) {
continue;
}
final DataStoreOperation<?, ?, ?> operation = operationResolver.resolve(method);
//noinspection unchecked
invocationMappings.add(
new ImmutableInvocationMapping<>(
method, (DataStoreOperation<?, Object, Object>) operation));
}
return invocationMappings;
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultResultAdapterContext.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultResultAdapterContext.java | package com.mmnaseri.utils.spring.data.proxy.impl;
import com.mmnaseri.utils.spring.data.domain.Invocation;
import com.mmnaseri.utils.spring.data.error.ResultAdapterFailureException;
import com.mmnaseri.utils.spring.data.proxy.ResultAdapter;
import com.mmnaseri.utils.spring.data.proxy.ResultAdapterContext;
import com.mmnaseri.utils.spring.data.proxy.impl.adapters.CollectionIterableResultAdapter;
import com.mmnaseri.utils.spring.data.proxy.impl.adapters.FutureIterableResultAdapter;
import com.mmnaseri.utils.spring.data.proxy.impl.adapters.GeoPageIterableResultAdapter;
import com.mmnaseri.utils.spring.data.proxy.impl.adapters.IteratorIterableResultAdapter;
import com.mmnaseri.utils.spring.data.proxy.impl.adapters.ListenableFutureIterableResultAdapter;
import com.mmnaseri.utils.spring.data.proxy.impl.adapters.NullSimpleResultAdapter;
import com.mmnaseri.utils.spring.data.proxy.impl.adapters.NullToCollectionResultAdapter;
import com.mmnaseri.utils.spring.data.proxy.impl.adapters.NullToFutureResultAdapter;
import com.mmnaseri.utils.spring.data.proxy.impl.adapters.NullToIterableResultAdapter;
import com.mmnaseri.utils.spring.data.proxy.impl.adapters.NullToIteratorResultAdapter;
import com.mmnaseri.utils.spring.data.proxy.impl.adapters.NullToListenableFutureResultAdapter;
import com.mmnaseri.utils.spring.data.proxy.impl.adapters.NullToSliceResultAdapter;
import com.mmnaseri.utils.spring.data.proxy.impl.adapters.NumberIterableResultAdapter;
import com.mmnaseri.utils.spring.data.proxy.impl.adapters.OptionalResultAdapter;
import com.mmnaseri.utils.spring.data.proxy.impl.adapters.PageIterableResultAdapter;
import com.mmnaseri.utils.spring.data.proxy.impl.adapters.SameTypeResultAdapter;
import com.mmnaseri.utils.spring.data.proxy.impl.adapters.SimpleIterableResultAdapter;
import com.mmnaseri.utils.spring.data.proxy.impl.adapters.SliceIterableResultAdapter;
import com.mmnaseri.utils.spring.data.proxy.impl.adapters.VoidResultAdapter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* This is the default implementation for registering and containing result adapters.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/24/15)
*/
@SuppressWarnings("WeakerAccess")
public class DefaultResultAdapterContext implements ResultAdapterContext {
private static final Log log = LogFactory.getLog(DefaultResultAdapterContext.class);
private final List<ResultAdapter<?>> adapters;
/** Instantiates the context and registers all the default adapters. */
public DefaultResultAdapterContext() {
this(true);
}
/**
* Instantiates the context
*
* @param registerDefaults whether default adapters should be registered by default.
*/
public DefaultResultAdapterContext(boolean registerDefaults) {
adapters = new ArrayList<>();
if (registerDefaults) {
adapters.add(new VoidResultAdapter());
adapters.add(new SameTypeResultAdapter());
adapters.add(new NullSimpleResultAdapter());
adapters.add(new NullToIteratorResultAdapter());
adapters.add(new NullToCollectionResultAdapter());
adapters.add(new NullToIterableResultAdapter());
adapters.add(new NullToSliceResultAdapter());
adapters.add(new NullToFutureResultAdapter());
adapters.add(new NullToListenableFutureResultAdapter());
adapters.add(new NumberIterableResultAdapter());
adapters.add(new SimpleIterableResultAdapter());
adapters.add(new OptionalResultAdapter());
adapters.add(new IteratorIterableResultAdapter());
adapters.add(new CollectionIterableResultAdapter());
adapters.add(new SliceIterableResultAdapter());
adapters.add(new PageIterableResultAdapter());
adapters.add(new GeoPageIterableResultAdapter());
adapters.add(new FutureIterableResultAdapter());
adapters.add(new ListenableFutureIterableResultAdapter());
Collections.sort(adapters);
}
}
@Override
public synchronized void register(ResultAdapter<?> adapter) {
log.info("Registering adapter " + adapter + " with the registry");
adapters.add(adapter);
Collections.sort(adapters);
}
@Override
public Object adapt(Invocation invocation, Object originalResult) {
log.info("Adapting the result of invocation to type " + invocation.getMethod().getReturnType());
for (ResultAdapter<?> adapter : adapters) {
if (adapter.accepts(invocation, originalResult)) {
return adapter.adapt(invocation, originalResult);
}
}
log.error(
"Could not find any result adapter that was capable of adapting the result of the invocation to type "
+ invocation.getMethod().getReturnType());
throw new ResultAdapterFailureException(originalResult, invocation.getMethod().getReturnType());
}
@Override
public Collection<ResultAdapter<?>> getAdapters() {
return Collections.unmodifiableCollection(adapters);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/NonDataOperationInvocationHandler.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/NonDataOperationInvocationHandler.java | package com.mmnaseri.utils.spring.data.proxy.impl;
import com.mmnaseri.utils.spring.data.error.UnknownDataOperationException;
import com.mmnaseri.utils.spring.data.proxy.NonDataOperationHandler;
import com.mmnaseri.utils.spring.data.proxy.impl.regular.EqualsNonDataOperationHandler;
import com.mmnaseri.utils.spring.data.proxy.impl.regular.HashCodeNonDataOperationHandler;
import com.mmnaseri.utils.spring.data.proxy.impl.regular.InterfaceDefaultMethodNonDataOperation;
import com.mmnaseri.utils.spring.data.proxy.impl.regular.ToStringNonDataOperationHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/**
* This class will handle invocations that are strictly non-data-related.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/8/16)
*/
public class NonDataOperationInvocationHandler implements InvocationHandler {
private static final Log log = LogFactory.getLog(NonDataOperationInvocationHandler.class);
private final List<NonDataOperationHandler> handlers;
public NonDataOperationInvocationHandler() {
this(true);
}
public NonDataOperationInvocationHandler(boolean registerDefaults) {
handlers = new LinkedList<>();
if (registerDefaults) {
log.info("Registering all the default operation handlers");
handlers.add(new EqualsNonDataOperationHandler());
handlers.add(new HashCodeNonDataOperationHandler());
handlers.add(new ToStringNonDataOperationHandler());
handlers.add(new InterfaceDefaultMethodNonDataOperation());
}
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) {
log.info("Intercepting non-data method " + method);
for (NonDataOperationHandler handler : handlers) {
if (handler.handles(proxy, method, args)) {
log.info("Found handler " + handler + " for method " + method);
return handler.invoke(proxy, method, args);
}
}
log.error("No data or non-data operation handler could be found for method " + method);
throw new UnknownDataOperationException(method);
}
public void register(NonDataOperationHandler handler) {
log.info("Registering operation handler " + handler);
handlers.add(handler);
}
public List<NonDataOperationHandler> getHandlers() {
return Collections.unmodifiableList(handlers);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableRepositoryConfiguration.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableRepositoryConfiguration.java | package com.mmnaseri.utils.spring.data.proxy.impl;
import com.mmnaseri.utils.spring.data.domain.KeyGenerator;
import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata;
import com.mmnaseri.utils.spring.data.proxy.RepositoryConfiguration;
import java.util.List;
/**
* This class is an immutable repository configuration.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/12/15)
*/
public class ImmutableRepositoryConfiguration implements RepositoryConfiguration {
private final RepositoryMetadata repositoryMetadata;
private final KeyGenerator<?> keyGenerator;
private final List<Class<?>> boundImplementations;
public ImmutableRepositoryConfiguration(
RepositoryMetadata repositoryMetadata,
KeyGenerator<?> keyGenerator,
List<Class<?>> boundImplementations) {
this.repositoryMetadata = repositoryMetadata;
this.keyGenerator = keyGenerator;
this.boundImplementations = boundImplementations;
}
@Override
public RepositoryMetadata getRepositoryMetadata() {
return repositoryMetadata;
}
@Override
public KeyGenerator<?> getKeyGenerator() {
return keyGenerator;
}
@Override
public List<Class<?>> getBoundImplementations() {
return boundImplementations;
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultTypeMappingContext.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultTypeMappingContext.java | package com.mmnaseri.utils.spring.data.proxy.impl;
import com.mmnaseri.utils.spring.data.error.RepositoryDefinitionException;
import com.mmnaseri.utils.spring.data.proxy.TypeMapping;
import com.mmnaseri.utils.spring.data.proxy.TypeMappingContext;
import com.mmnaseri.utils.spring.data.repository.DefaultCrudRepository;
import com.mmnaseri.utils.spring.data.repository.DefaultGemfireRepository;
import com.mmnaseri.utils.spring.data.repository.DefaultJpaRepository;
import com.mmnaseri.utils.spring.data.repository.DefaultPagingAndSortingRepository;
import com.mmnaseri.utils.spring.data.repository.DefaultQueryByExampleExecutor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.util.ClassUtils;
import java.lang.reflect.Modifier;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* This is the default type mapping context that is also capable of registering the default mappings
* for the interfaces provided through Spring Data.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/8/15)
*/
@SuppressWarnings("WeakerAccess")
public class DefaultTypeMappingContext implements TypeMappingContext {
private static final Log log = LogFactory.getLog(DefaultTypeMappingContext.class);
private static final String GEMFIRE_SUPPORT_CLASS =
"org.springframework.data.gemfire.repository.GemfireRepository";
private static final String JPA_SUPPORT_CLASS =
"org.springframework.data.jpa.repository.JpaRepository";
private static final String QUERY_BY_EXAMPLE_SUPPORT_CLASS =
"org.springframework.data.repository.query.QueryByExampleExecutor";
private final TypeMappingContext parent;
private final ConcurrentMap<Class<?>, List<Class<?>>> mappings = new ConcurrentHashMap<>();
/** Instantiates the context and registers all the default converters */
public DefaultTypeMappingContext() {
this(true);
}
/**
* Instantiates the context
*
* @param registerDefaults whether or not the default mappings should be registered.
*/
public DefaultTypeMappingContext(boolean registerDefaults) {
this(null);
if (registerDefaults) {
log.info("Trying to register all the default type mappings");
if (isClassPresent(GEMFIRE_SUPPORT_CLASS)) {
log.debug(
"We seem to have Gemfire in the classpath, so, we should register the supporting registry");
register(Object.class, DefaultGemfireRepository.class);
}
if (isClassPresent(JPA_SUPPORT_CLASS)) {
log.debug("JPA support is enabled in this project, so we need to support the methods");
register(Object.class, DefaultJpaRepository.class);
}
if (isClassPresent(QUERY_BY_EXAMPLE_SUPPORT_CLASS)) {
log.debug("Query by example is enabled. We will the proper method implementations.");
register(Object.class, DefaultQueryByExampleExecutor.class);
}
register(Object.class, DefaultPagingAndSortingRepository.class);
register(Object.class, DefaultCrudRepository.class);
}
}
public DefaultTypeMappingContext(TypeMappingContext parent) {
this.parent = parent;
}
private boolean isClassPresent(String className) {
return ClassUtils.isPresent(className, ClassUtils.getDefaultClassLoader());
}
@Override
public void register(Class<?> repositoryType, Class<?> implementation) {
if (Modifier.isAbstract(implementation.getModifiers())
|| Modifier.isInterface(implementation.getModifiers())) {
log.error("Cannot bind a non-concrete class as an implementation for a non-concrete class");
throw new RepositoryDefinitionException(
repositoryType,
"Cannot bind a non-concrete class as an implementation for a " + "non-concrete class");
}
log.info(
"Registering implementation "
+ implementation
+ " to super type "
+ repositoryType
+ "; this means any repository of this type will inherit functionality defined in the "
+ "bound implementation class.");
mappings.putIfAbsent(repositoryType, new LinkedList<>());
mappings.get(repositoryType).add(implementation);
}
@Override
public List<Class<?>> getImplementations(Class<?> repositoryType) {
final List<Class<?>> classes = new LinkedList<>();
for (Class<?> repositorySuperType : mappings.keySet()) {
if (repositorySuperType.isAssignableFrom(repositoryType)) {
classes.addAll(mappings.get(repositorySuperType));
}
}
classes.sort(AnnotationAwareOrderComparator.INSTANCE);
if (parent != null) {
classes.addAll(parent.getImplementations(repositoryType));
}
return classes;
}
@Override
public List<TypeMapping<?>> getMappings(Class<?> repositoryType) {
final List<TypeMapping<?>> typeMappings = new LinkedList<>();
final List<Class<?>> implementations = getImplementations(repositoryType);
log.info(
"The repository " + repositoryType + " is bound to implementations " + implementations);
for (Class<?> implementation : implementations) {
final Object instance;
try {
instance = implementation.getDeclaredConstructor().newInstance();
} catch (IllegalAccessException e) {
log.error(
"The constructor for the implementation class is not accessible: " + implementation);
throw new RepositoryDefinitionException(
repositoryType, "Failed to access the constructor for " + implementation, e);
} catch (Exception e) {
log.error("The constructor for " + implementation + " threw an exception");
throw new RepositoryDefinitionException(
repositoryType, "Constructor threw an exception " + implementation, e);
}
//noinspection unchecked
typeMappings.add(new ImmutableTypeMapping<>((Class<Object>) implementation, instance));
}
return typeMappings;
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultRepositoryFactoryConfiguration.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultRepositoryFactoryConfiguration.java | package com.mmnaseri.utils.spring.data.proxy.impl;
import com.mmnaseri.utils.spring.data.domain.KeyGenerator;
import com.mmnaseri.utils.spring.data.domain.RepositoryMetadataResolver;
import com.mmnaseri.utils.spring.data.domain.impl.MethodQueryDescriptionExtractor;
import com.mmnaseri.utils.spring.data.proxy.RepositoryFactoryConfiguration;
import com.mmnaseri.utils.spring.data.proxy.ResultAdapterContext;
import com.mmnaseri.utils.spring.data.proxy.TypeMappingContext;
import com.mmnaseri.utils.spring.data.query.DataFunctionRegistry;
import com.mmnaseri.utils.spring.data.store.DataStoreEventListenerContext;
import com.mmnaseri.utils.spring.data.store.DataStoreRegistry;
/**
* This is a configurable (mutable) repository factory configuration
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/27/15)
*/
public class DefaultRepositoryFactoryConfiguration implements RepositoryFactoryConfiguration {
private RepositoryMetadataResolver repositoryMetadataResolver;
private MethodQueryDescriptionExtractor descriptionExtractor;
private DataFunctionRegistry functionRegistry;
private DataStoreRegistry dataStoreRegistry;
private ResultAdapterContext resultAdapterContext;
private TypeMappingContext typeMappingContext;
private DataStoreEventListenerContext eventListenerContext;
private NonDataOperationInvocationHandler operationInvocationHandler;
private KeyGenerator<?> defaultKeyGenerator;
public DefaultRepositoryFactoryConfiguration() {}
public DefaultRepositoryFactoryConfiguration(RepositoryFactoryConfiguration configuration) {
this(
configuration.getRepositoryMetadataResolver(),
configuration.getDescriptionExtractor(),
configuration.getFunctionRegistry(),
configuration.getDataStoreRegistry(),
configuration.getResultAdapterContext(),
configuration.getTypeMappingContext(),
configuration.getEventListenerContext(),
configuration.getOperationInvocationHandler(),
configuration.getDefaultKeyGenerator());
}
public DefaultRepositoryFactoryConfiguration(
RepositoryMetadataResolver repositoryMetadataResolver,
MethodQueryDescriptionExtractor descriptionExtractor,
DataFunctionRegistry functionRegistry,
DataStoreRegistry dataStoreRegistry,
ResultAdapterContext resultAdapterContext,
TypeMappingContext typeMappingContext,
DataStoreEventListenerContext eventListenerContext,
NonDataOperationInvocationHandler operationInvocationHandler,
KeyGenerator<?> defaultKeyGenerator) {
this.repositoryMetadataResolver = repositoryMetadataResolver;
this.descriptionExtractor = descriptionExtractor;
this.functionRegistry = functionRegistry;
this.dataStoreRegistry = dataStoreRegistry;
this.resultAdapterContext = resultAdapterContext;
this.typeMappingContext = typeMappingContext;
this.eventListenerContext = eventListenerContext;
this.operationInvocationHandler = operationInvocationHandler;
this.defaultKeyGenerator = defaultKeyGenerator;
}
@Override
public RepositoryMetadataResolver getRepositoryMetadataResolver() {
return repositoryMetadataResolver;
}
public void setRepositoryMetadataResolver(RepositoryMetadataResolver repositoryMetadataResolver) {
this.repositoryMetadataResolver = repositoryMetadataResolver;
}
@Override
public MethodQueryDescriptionExtractor getDescriptionExtractor() {
return descriptionExtractor;
}
public void setDescriptionExtractor(MethodQueryDescriptionExtractor descriptionExtractor) {
this.descriptionExtractor = descriptionExtractor;
}
@Override
public DataFunctionRegistry getFunctionRegistry() {
return functionRegistry;
}
public void setFunctionRegistry(DataFunctionRegistry functionRegistry) {
this.functionRegistry = functionRegistry;
}
@Override
public DataStoreRegistry getDataStoreRegistry() {
return dataStoreRegistry;
}
public void setDataStoreRegistry(DataStoreRegistry dataStoreRegistry) {
this.dataStoreRegistry = dataStoreRegistry;
}
@Override
public ResultAdapterContext getResultAdapterContext() {
return resultAdapterContext;
}
public void setResultAdapterContext(ResultAdapterContext resultAdapterContext) {
this.resultAdapterContext = resultAdapterContext;
}
@Override
public TypeMappingContext getTypeMappingContext() {
return typeMappingContext;
}
public void setTypeMappingContext(TypeMappingContext typeMappingContext) {
this.typeMappingContext = typeMappingContext;
}
@Override
public DataStoreEventListenerContext getEventListenerContext() {
return eventListenerContext;
}
public void setEventListenerContext(DataStoreEventListenerContext eventListenerContext) {
this.eventListenerContext = eventListenerContext;
}
@Override
public NonDataOperationInvocationHandler getOperationInvocationHandler() {
return operationInvocationHandler;
}
public void setOperationInvocationHandler(
NonDataOperationInvocationHandler operationInvocationHandler) {
this.operationInvocationHandler = operationInvocationHandler;
}
@Override
public KeyGenerator<?> getDefaultKeyGenerator() {
return defaultKeyGenerator;
}
public void setDefaultKeyGenerator(KeyGenerator<?> defaultKeyGenerator) {
this.defaultKeyGenerator = defaultKeyGenerator;
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/DataOperationInvocationHandler.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/DataOperationInvocationHandler.java | package com.mmnaseri.utils.spring.data.proxy.impl;
import com.mmnaseri.utils.spring.data.domain.Invocation;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableInvocation;
import com.mmnaseri.utils.spring.data.proxy.InvocationMapping;
import com.mmnaseri.utils.spring.data.proxy.RepositoryConfiguration;
import com.mmnaseri.utils.spring.data.proxy.ResultAdapterContext;
import com.mmnaseri.utils.spring.data.proxy.ResultConverter;
import com.mmnaseri.utils.spring.data.proxy.impl.converters.DefaultResultConverter;
import com.mmnaseri.utils.spring.data.store.DataStore;
import com.mmnaseri.utils.spring.data.store.DataStoreOperation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* This class is in charge of handling a data operation that was triggered by invoking a repository
* method.
*
* <p>The invocation is first considered by trying to find a data operation handler. If such a
* handler cannot be found, we will try to handle it by finding the appropriate {@link
* com.mmnaseri.utils.spring.data.proxy.NonDataOperationHandler non-data operation handler}.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/23/15)
*/
@SuppressWarnings("WeakerAccess")
public class DataOperationInvocationHandler<K, E> implements InvocationHandler {
private static final Log log = LogFactory.getLog(DataOperationInvocationHandler.class);
private final DataStore<K, E> dataStore;
private final ResultAdapterContext adapterContext;
private final ResultConverter converter;
private final RepositoryConfiguration repositoryConfiguration;
private final List<InvocationMapping<K, E>> mappings;
private final Map<Method, InvocationMapping<K, E>> cache = new ConcurrentHashMap<>();
private final Set<Method> misses = new CopyOnWriteArraySet<>();
private final NonDataOperationInvocationHandler operationInvocationHandler;
public DataOperationInvocationHandler(
RepositoryConfiguration repositoryConfiguration,
List<InvocationMapping<K, E>> mappings,
DataStore<K, E> dataStore,
ResultAdapterContext adapterContext,
NonDataOperationInvocationHandler operationInvocationHandler) {
this.repositoryConfiguration = repositoryConfiguration;
this.mappings = mappings;
this.dataStore = dataStore;
this.adapterContext = adapterContext;
this.operationInvocationHandler = operationInvocationHandler;
this.converter = new DefaultResultConverter();
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) {
log.info(
"A method call to "
+ method
+ " has been intercepted. We will now try to find an appropriate invocation.");
final Invocation methodInvocation = new ImmutableInvocation(method, args);
InvocationMapping<K, E> targetMapping = null;
if (!misses.contains(method)) {
if (cache.containsKey(method)) {
targetMapping = cache.get(method);
} else {
for (InvocationMapping<K, E> mapping : mappings) {
if (mapping.getMethod().equals(method)) {
targetMapping = mapping;
cache.put(method, targetMapping);
break;
}
}
}
}
if (targetMapping == null) {
log.info(
"The invocation cannot be resolved using a data operation. We will try to handle this as a "
+ "non-data operation");
misses.add(method);
return operationInvocationHandler.invoke(proxy, method, args);
}
final DataStoreOperation<?, K, E> operation = targetMapping.getOperation();
log.info("Executing the operation for method " + method);
final Object operationResult =
operation.execute(dataStore, repositoryConfiguration, methodInvocation);
log.info("Trying to see if any conversion is necessary on the object");
final Object convertedResult = converter.convert(methodInvocation, operationResult);
return adapterContext.adapt(methodInvocation, convertedResult);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableInvocationMapping.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableInvocationMapping.java | package com.mmnaseri.utils.spring.data.proxy.impl;
import com.mmnaseri.utils.spring.data.proxy.InvocationMapping;
import com.mmnaseri.utils.spring.data.store.DataStoreOperation;
import java.lang.reflect.Method;
/**
* This class is an immutable invocation mapping.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/29/15)
*/
@SuppressWarnings("WeakerAccess")
public class ImmutableInvocationMapping<K, E> implements InvocationMapping<K, E> {
private final Method method;
private final DataStoreOperation<?, K, E> operation;
public ImmutableInvocationMapping(Method method, DataStoreOperation<?, K, E> operation) {
this.method = method;
this.operation = operation;
}
@Override
public Method getMethod() {
return method;
}
@Override
public DataStoreOperation<?, K, E> getOperation() {
return operation;
}
@Override
public String toString() {
return method + " -> " + operation;
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/IteratorToIterableConverter.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/IteratorToIterableConverter.java | package com.mmnaseri.utils.spring.data.proxy.impl.converters;
import com.mmnaseri.utils.spring.data.domain.Invocation;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* This value will convert an iterator to an iterable.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/28/15)
*/
@SuppressWarnings("WeakerAccess")
public class IteratorToIterableConverter extends AbstractResultConverter {
@Override
protected Object doConvert(Invocation invocation, Object original) {
if (original instanceof Iterator) {
Iterator iterator = (Iterator) original;
final List<Object> list = new LinkedList<>();
while (iterator.hasNext()) {
list.add(iterator.next());
}
return list;
}
return original;
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/FutureToIterableConverter.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/FutureToIterableConverter.java | package com.mmnaseri.utils.spring.data.proxy.impl.converters;
import com.mmnaseri.utils.spring.data.domain.Invocation;
import com.mmnaseri.utils.spring.data.error.ResultConversionFailureException;
import com.mmnaseri.utils.spring.data.proxy.ResultConverter;
import java.util.concurrent.Future;
/**
* This converter will convert a value that is of type {@link Future} to an iterable. Furthermore,
* it will convert that value one more level to get to the final value, if required. Also, the
* conversion will be a blocking statement that waits for the future value to be resolved via {@link
* Future#get()}.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/28/15)
*/
@SuppressWarnings("WeakerAccess")
public class FutureToIterableConverter extends AbstractResultConverter {
@Override
protected Object doConvert(Invocation invocation, Object original) {
if (original instanceof Future) {
Future future = (Future) original;
final ResultConverter converter = new DefaultResultConverter();
try {
final Object result = future.get();
return converter.convert(invocation, result);
} catch (Exception e) {
throw new ResultConversionFailureException(e);
}
}
return original;
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/AbstractResultConverter.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/AbstractResultConverter.java | package com.mmnaseri.utils.spring.data.proxy.impl.converters;
import com.mmnaseri.utils.spring.data.domain.Invocation;
import com.mmnaseri.utils.spring.data.proxy.ResultConverter;
/**
* This class will let us convert non-{@literal null} values if the invocation is not of type
* {@literal void}.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @see #doConvert(Invocation, Object)
* @since 1.0 (9/28/15)
*/
public abstract class AbstractResultConverter implements ResultConverter {
@Override
public Object convert(Invocation invocation, Object original) {
if (original == null || invocation.getMethod().getReturnType().equals(void.class)) {
return null;
}
if (invocation.getMethod().getReturnType().isInstance(original)) {
return original;
}
return doConvert(invocation, original);
}
/**
* Called to invoke a conversion of the given value to the desired result value.
*
* @param invocation the invocation
* @param original the original value
* @return the converted value
*/
protected abstract Object doConvert(Invocation invocation, Object original);
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/DefaultResultConverter.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/DefaultResultConverter.java | package com.mmnaseri.utils.spring.data.proxy.impl.converters;
import com.mmnaseri.utils.spring.data.domain.Invocation;
import com.mmnaseri.utils.spring.data.proxy.ResultConverter;
import java.util.LinkedList;
import java.util.List;
/**
* This class is the default result converter that also acts as a registry for other converters. It
* will execute the default converters in the following order
*
* <ol>
* <li>{@link FutureToIterableConverter}
* <li>{@link IteratorToIterableConverter}
* <li>{@link SingleValueToIterableConverter}
* </ol>
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/28/15)
*/
@SuppressWarnings("WeakerAccess")
public class DefaultResultConverter implements ResultConverter {
private final List<ResultConverter> converters;
/** Instantiates the converter and registers the default converters */
public DefaultResultConverter() {
this(true);
}
/**
* Instantiates the converter
*
* @param registerDefaults whether or not default converters should be registered
*/
public DefaultResultConverter(boolean registerDefaults) {
converters = new LinkedList<>();
if (registerDefaults) {
converters.add(new FutureToIterableConverter());
converters.add(new IteratorToIterableConverter());
converters.add(new SingleValueToIterableConverter());
}
}
@Override
public Object convert(Invocation invocation, Object original) {
Object value = original;
for (ResultConverter converter : converters) {
value = converter.convert(invocation, value);
}
return value;
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/SingleValueToIterableConverter.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/SingleValueToIterableConverter.java | package com.mmnaseri.utils.spring.data.proxy.impl.converters;
import com.mmnaseri.utils.spring.data.domain.Invocation;
import java.util.Collections;
import java.util.Iterator;
/**
* This value will create a {@link Collections#singletonList singleton list} out of the passed
* value, so long as it is not an iterable or iterator object.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/28/15)
*/
@SuppressWarnings("WeakerAccess")
public class SingleValueToIterableConverter extends AbstractResultConverter {
@Override
protected Object doConvert(Invocation invocation, Object original) {
if (original instanceof Iterable || original instanceof Iterator) {
return original;
}
return Collections.singletonList(original);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToCollectionResultAdapter.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToCollectionResultAdapter.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.Invocation;
import com.mmnaseri.utils.spring.data.tools.CollectionInstanceUtils;
import java.util.Collection;
/**
* This adapter will try to adapt a {@literal null} value to a collection.
*
* <p>It adapts results if the return type is of type {@link Collection} and the original value is
* {@literal null}.
*
* <p>This adapter runs at the priority of {@literal -300}.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/24/15)
*/
public class NullToCollectionResultAdapter extends AbstractResultAdapter<Collection> {
public NullToCollectionResultAdapter() {
super(-300);
}
@Override
public boolean accepts(Invocation invocation, Object originalValue) {
return originalValue == null
&& Collection.class.isAssignableFrom(invocation.getMethod().getReturnType());
}
@Override
public Collection adapt(Invocation invocation, Object originalValue) {
return CollectionInstanceUtils.getCollection(invocation.getMethod().getReturnType());
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToFutureResultAdapter.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToFutureResultAdapter.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.Invocation;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
/**
* This adapter will try to adapt a {@literal null} value to a future.
*
* <p>It adapts results if the return type is of type {@link Future} and the original value is
* {@literal null}.
*
* <p>This adapter runs at the priority of {@literal -150}.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/24/15)
*/
public class NullToFutureResultAdapter extends AbstractResultAdapter<Future> {
public NullToFutureResultAdapter() {
super(-150);
}
@Override
public boolean accepts(Invocation invocation, Object originalValue) {
return originalValue == null && invocation.getMethod().getReturnType().equals(Future.class);
}
@Override
public Future adapt(Invocation invocation, Object originalValue) {
//noinspection unchecked
final FutureTask task = new FutureTask(() -> null);
task.run();
return task;
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/SimpleIterableResultAdapter.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/SimpleIterableResultAdapter.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.Invocation;
import com.mmnaseri.utils.spring.data.error.ResultAdapterFailureException;
import com.mmnaseri.utils.spring.data.tools.PropertyUtils;
import java.util.Iterator;
import java.util.Optional;
import java.util.concurrent.Future;
/**
* This adapter accepts all invocations wherein the original value is an {@link Iterable} object and
* the requested method type is a simple value. Simple types are types that are not a subtype of
* {@link Iterable}, {@link Iterator}, {@link Future}, or {@link Optional}.
*
* <p>While adapting, the adapter will also check that the iterable yields only one item and that it
* is of the same type or of a child type of the type requested by the invoked method.
*
* <p>This adapter runs at the priority {@literal -400}.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/28/15)
*/
public class SimpleIterableResultAdapter extends AbstractIterableResultAdapter<Object> {
public SimpleIterableResultAdapter() {
super(-400);
}
@Override
public boolean accepts(Invocation invocation, Object originalValue) {
if (!(originalValue instanceof Iterable)) {
return false;
}
final Class<?> returnType = invocation.getMethod().getReturnType();
return !Iterable.class.isAssignableFrom(returnType)
&& !Iterator.class.isAssignableFrom(returnType)
&& !Future.class.isAssignableFrom(returnType)
&& !Optional.class.isAssignableFrom(returnType);
}
@Override
protected Object doAdapt(Invocation invocation, Iterable iterable) {
final Iterator iterator = iterable.iterator();
if (iterator.hasNext()) {
final Object value = iterator.next();
if (iterator.hasNext()) {
throw new ResultAdapterFailureException(
iterable,
invocation.getMethod().getReturnType(),
"Expected only one item but found many");
}
if (!PropertyUtils.getTypeOf(invocation.getMethod().getReturnType()).isInstance(value)) {
throw new ResultAdapterFailureException(
value,
invocation.getMethod().getReturnType(),
"Expected value to be of the indicated type");
}
return value;
} else {
return null;
}
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/EmptyIterator.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/EmptyIterator.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import java.util.Iterator;
/**
* This class is an iterator over an empty collection.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public class EmptyIterator implements Iterator {
/** This is the shared instance of the empty iterator */
public static final EmptyIterator INSTANCE = new EmptyIterator();
@Override
public boolean hasNext() {
return false;
}
@Override
public Object next() {
throw new IndexOutOfBoundsException();
}
@Override
public void remove() {
throw new IndexOutOfBoundsException();
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/PageIterableResultAdapter.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/PageIterableResultAdapter.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.Invocation;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import java.util.ArrayList;
import java.util.List;
/**
* This class will adapt results from an iterable object to a page.
*
* <p>It will accept adaptations wherein the original value is some sort of iterable and the
* required return type is an instance of {@link Page}. Remember that it does <em>not</em> check for
* individual object type compatibility.
*
* <p>This adapter will execute at priority {@literal -200}.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/28/15)
*/
public class PageIterableResultAdapter extends AbstractIterableResultAdapter<Page> {
public PageIterableResultAdapter() {
super(-200);
}
@Override
protected Page doAdapt(Invocation invocation, Iterable iterable) {
final List content = new ArrayList();
for (Object item : iterable) {
//noinspection unchecked
content.add(item);
}
//noinspection unchecked
return new PageImpl(content);
}
@Override
public boolean accepts(Invocation invocation, Object originalValue) {
return originalValue instanceof Iterable
&& invocation.getMethod().getReturnType().equals(Page.class);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/AbstractResultAdapter.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/AbstractResultAdapter.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.proxy.ResultAdapter;
/**
* This is the base class for all result adapters that adds comparison capabilities to teh adapters.
* This basically means that now adapters can be compared using their assigned priorities.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/24/15)
*/
public abstract class AbstractResultAdapter<E> implements ResultAdapter<E> {
private final int priority;
public AbstractResultAdapter(int priority) {
this.priority = priority;
}
@Override
public int compareTo(ResultAdapter that) {
return Integer.compare(getPriority(), that.getPriority());
}
@Override
public int getPriority() {
return priority;
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/OptionalResultAdapter.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/OptionalResultAdapter.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.Invocation;
import com.mmnaseri.utils.spring.data.error.ResultAdapterFailureException;
import java.util.Iterator;
import java.util.Optional;
/**
* This adapter accepts all invocations wherein the original value is an {@link Iterable} object and
* the requested method type is an {@link Optional} value.
*
* <p>While adapting, the adapter will also check that the iterable yields only one item and that it
* is of the same type or of a child type of the type requested by the invoked method.
*
* <p>This adapter runs at the priority {@literal -400}.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 2.1.1 (10/29/2020)
*/
public class OptionalResultAdapter extends AbstractIterableResultAdapter<Object> {
public OptionalResultAdapter() {
super(-400);
}
@Override
public boolean accepts(final Invocation invocation, final Object originalValue) {
if (!(originalValue instanceof Iterable)) {
return false;
}
final Class<?> returnType = invocation.getMethod().getReturnType();
return returnType.isAssignableFrom(Optional.class);
}
@Override
protected Object doAdapt(final Invocation invocation, final Iterable iterable) {
final Iterator iterator = iterable.iterator();
if (iterator.hasNext()) {
final Object value = iterator.next();
if (iterator.hasNext()) {
throw new ResultAdapterFailureException(
iterable,
invocation.getMethod().getReturnType(),
"Expected only one item but found many");
}
return Optional.of(value);
} else {
return Optional.empty();
}
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToIterableResultAdapter.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToIterableResultAdapter.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.Invocation;
import java.util.Collections;
/**
* This adapter will try to adapt a {@literal null} value to an iterable.
*
* <p>It adapts results if the return type is of type {@link Iterable} and the original value is
* {@literal null}.
*
* <p>This adapter runs at the priority of {@literal -250}.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/24/15)
*/
public class NullToIterableResultAdapter extends AbstractResultAdapter<Iterable> {
public NullToIterableResultAdapter() {
super(-250);
}
@Override
public boolean accepts(Invocation invocation, Object originalValue) {
return invocation.getMethod().getReturnType().equals(Iterable.class) && originalValue == null;
}
@Override
public Iterable adapt(Invocation invocation, Object originalValue) {
return Collections.emptyList();
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/IteratorIterableResultAdapter.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/IteratorIterableResultAdapter.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.Invocation;
import java.util.Iterator;
/**
* This class will adapt results from an iterable object to an iterator.
*
* <p>It will accept adaptations wherein the original value is some sort of iterable and the
* required return type is an instance of {@link Iterator}. Remember that it does <em>not</em> check
* for individual object type compatibility.
*
* <p>This adapter will execute at priority {@literal -350}.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/28/15)
*/
public class IteratorIterableResultAdapter extends AbstractIterableResultAdapter<Iterator> {
public IteratorIterableResultAdapter() {
super(-350);
}
@Override
public boolean accepts(Invocation invocation, Object originalValue) {
return originalValue instanceof Iterable
&& Iterator.class.equals(invocation.getMethod().getReturnType());
}
@Override
protected Iterator doAdapt(Invocation invocation, Iterable iterable) {
return iterable.iterator();
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToSliceResultAdapter.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToSliceResultAdapter.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.Invocation;
import org.springframework.data.domain.Slice;
import org.springframework.data.geo.GeoPage;
import org.springframework.data.geo.GeoResults;
import java.util.Collections;
/**
* This adapter will try to adapt a {@literal null} value to a slice.
*
* <p>It adapts results if the return type is of type {@link Slice} and the original value is
* {@literal null}.
*
* <p>This adapter runs at the priority of {@literal -200}.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/24/15)
*/
public class NullToSliceResultAdapter extends AbstractResultAdapter<Slice> {
public NullToSliceResultAdapter() {
super(-200);
}
@Override
public boolean accepts(Invocation invocation, Object originalValue) {
return originalValue == null
&& Slice.class.isAssignableFrom(invocation.getMethod().getReturnType());
}
@Override
public Slice adapt(Invocation invocation, Object originalValue) {
//noinspection unchecked
return new GeoPage(new GeoResults(Collections.emptyList()));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/SameTypeResultAdapter.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/SameTypeResultAdapter.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.Invocation;
/**
* This adapter will accept and adapt results when the request result type is of the same type or a
* super type of the available value.
*
* <p>This adapter runs at priority {@literal -500}.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/24/15)
*/
public class SameTypeResultAdapter extends AbstractResultAdapter<Object> {
public SameTypeResultAdapter() {
super(-500);
}
@Override
public boolean accepts(Invocation invocation, Object originalValue) {
return originalValue != null
&& invocation.getMethod().getReturnType().isInstance(originalValue);
}
@Override
public Object adapt(Invocation invocation, Object originalValue) {
return originalValue;
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/GeoPageIterableResultAdapter.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/GeoPageIterableResultAdapter.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.Invocation;
import org.springframework.data.geo.GeoPage;
import org.springframework.data.geo.GeoResults;
import java.util.ArrayList;
import java.util.List;
/**
* This class will adapt results from an iterable object to a geo page.
*
* <p>It will accept adaptations wherein the original value is some sort of iterable and the
* required return type is an instance of {@link GeoPage}. Remember that it does <em>not</em> check
* for individual object type compatibility.
*
* <p>This adapter will execute at priority {@literal -150}.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/28/15)
*/
public class GeoPageIterableResultAdapter extends AbstractIterableResultAdapter<GeoPage> {
public GeoPageIterableResultAdapter() {
super(-150);
}
@Override
protected GeoPage doAdapt(Invocation invocation, Iterable iterable) {
final List content = new ArrayList();
for (Object item : iterable) {
//noinspection unchecked
content.add(item);
}
//noinspection unchecked
return new GeoPage(new GeoResults(content));
}
@Override
public boolean accepts(Invocation invocation, Object originalValue) {
return originalValue instanceof Iterable
&& invocation.getMethod().getReturnType().equals(GeoPage.class);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NumberIterableResultAdapter.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NumberIterableResultAdapter.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.Invocation;
import com.mmnaseri.utils.spring.data.error.ResultAdapterFailureException;
import com.mmnaseri.utils.spring.data.tools.PropertyUtils;
import java.util.Iterator;
/**
* This class will adapt results from an iterable object to a number. The future task returned will
* have already executed with the results available.
*
* <p>It will accept adaptations wherein the original value is some sort of iterable and the
* required return type is an instance of {@link Number}. Additionally, it will check to see if the
* iterable yields only one item and also that the item is a number.
*
* <p>Here is a list of supported number types:
*
* <ul>
* <li>{@link Long}
* <li>{@link Short}
* <li>{@link Integer}
* <li>{@link Byte}
* <li>{@link Double}
* <li>{@link Float}
* </ul>
*
* <p>This adapter will execute at priority {@literal -425}.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/12/15)
*/
public class NumberIterableResultAdapter extends AbstractIterableResultAdapter<Object> {
public NumberIterableResultAdapter() {
super(-425);
}
@Override
protected Object doAdapt(Invocation invocation, Iterable iterable) {
final Iterator iterator = iterable.iterator();
final Object value = iterator.next();
final Number number = (Number) value;
final Class<?> returnType = PropertyUtils.getTypeOf(invocation.getMethod().getReturnType());
if (Long.class.equals(returnType)) {
return number.longValue();
} else if (Short.class.equals(returnType)) {
return number.shortValue();
} else if (Integer.class.equals(returnType)) {
return number.intValue();
} else if (Byte.class.equals(returnType)) {
return number.byteValue();
} else if (Double.class.equals(returnType)) {
return number.doubleValue();
} else if (Float.class.equals(returnType)) {
return number.floatValue();
}
throw new ResultAdapterFailureException(value, returnType);
}
@Override
public boolean accepts(Invocation invocation, Object originalValue) {
if (originalValue == null) {
return false;
}
if (!Number.class.isAssignableFrom(
PropertyUtils.getTypeOf(invocation.getMethod().getReturnType()))) {
return false;
}
if (originalValue instanceof Iterable) {
Iterable iterable = (Iterable) originalValue;
final Iterator iterator = iterable.iterator();
if (iterator.hasNext()) {
final Object value = iterator.next();
return value instanceof Number && !iterator.hasNext();
}
}
return false;
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/SliceIterableResultAdapter.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/SliceIterableResultAdapter.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.Invocation;
import org.springframework.data.domain.Slice;
import org.springframework.data.domain.SliceImpl;
import java.util.ArrayList;
import java.util.List;
/**
* This class will adapt results from an iterable object to a slice.
*
* <p>It will accept adaptations wherein the original value is some sort of iterable and the
* required return type is an instance of {@link Slice}. Remember that it does <em>not</em> check
* for individual object type compatibility.
*
* <p>This adapter will execute at priority {@literal -250}.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/28/15)
*/
public class SliceIterableResultAdapter extends AbstractIterableResultAdapter<Slice> {
public SliceIterableResultAdapter() {
super(-250);
}
@Override
protected Slice doAdapt(Invocation invocation, Iterable iterable) {
final List content = new ArrayList();
for (Object item : iterable) {
//noinspection unchecked
content.add(item);
}
//noinspection unchecked
return new SliceImpl(content);
}
@Override
public boolean accepts(Invocation invocation, Object originalValue) {
return originalValue instanceof Iterable
&& invocation.getMethod().getReturnType().equals(Slice.class);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/ListenableFutureIterableResultAdapter.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/ListenableFutureIterableResultAdapter.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.Invocation;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureTask;
import java.util.concurrent.Callable;
/**
* This class will adapt results from an iterable object to a <em>listenable</em> future. The future
* task returned will have already executed with the results available.
*
* <p>It will accept adaptations wherein the original value is some sort of iterable and the
* required return type is an instance of {@link ListenableFuture}. Remember that it does
* <em>not</em> check for individual object type compatibility.
*
* <p>This adapter will execute at priority {@literal -50}.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/28/15)
*/
public class ListenableFutureIterableResultAdapter
extends AbstractIterableResultAdapter<ListenableFuture> {
public ListenableFutureIterableResultAdapter() {
super(-50);
}
@Override
protected ListenableFuture doAdapt(Invocation invocation, final Iterable iterable) {
final ListenableFutureTask task = new ListenableFutureTask<>((Callable<Object>) () -> iterable);
task.run();
return task;
}
@Override
public boolean accepts(Invocation invocation, Object originalValue) {
return originalValue instanceof Iterable
&& invocation.getMethod().getReturnType().equals(ListenableFuture.class);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullSimpleResultAdapter.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullSimpleResultAdapter.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.Invocation;
import com.mmnaseri.utils.spring.data.error.ResultAdapterFailureException;
import java.util.Iterator;
import java.util.concurrent.Future;
/**
* This adapter will try to adapt a {@literal null} value to a simple value. Simple here is defined
* as anything that is not an iterable, an iterator, or a future promise.
*
* <p>It adapts results if the return type is simple and the original value is {@literal null}.
*
* <p>This adapter runs at the priority of {@literal -400}.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/24/15)
*/
public class NullSimpleResultAdapter extends AbstractResultAdapter<Object> {
public NullSimpleResultAdapter() {
super(-400);
}
@Override
public boolean accepts(Invocation invocation, Object originalValue) {
final Class<?> returnType = invocation.getMethod().getReturnType();
return !Iterable.class.isAssignableFrom(returnType)
&& !Iterator.class.isAssignableFrom(returnType)
&& !Future.class.isAssignableFrom(returnType)
&& originalValue == null;
}
@Override
public Object adapt(Invocation invocation, Object originalValue) {
if (invocation.getMethod().getReturnType().isPrimitive()) {
throw new ResultAdapterFailureException(null, invocation.getMethod().getReturnType());
}
return null;
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/FutureIterableResultAdapter.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/FutureIterableResultAdapter.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.Invocation;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
/**
* This class will adapt results from an iterable object to a future. The future task returned will
* have already executed with the results available.
*
* <p>It will accept adaptations wherein the original value is some sort of iterable and the
* required return type is an instance of {@link Future}. Remember that it does <em>not</em> check
* for individual object type compatibility.
*
* <p>This adapter will execute at priority {@literal -100}.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/28/15)
*/
public class FutureIterableResultAdapter extends AbstractIterableResultAdapter<Future> {
public FutureIterableResultAdapter() {
super(-100);
}
@Override
protected Future doAdapt(Invocation invocation, final Iterable iterable) {
//noinspection unchecked
final FutureTask task = new FutureTask(() -> iterable);
task.run();
return task;
}
@Override
public boolean accepts(Invocation invocation, Object originalValue) {
return originalValue instanceof Iterable
&& invocation.getMethod().getReturnType().equals(Future.class);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToIteratorResultAdapter.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToIteratorResultAdapter.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.Invocation;
import java.util.Iterator;
/**
* This adapter will try to adapt a {@literal null} value to an iterator.
*
* <p>It adapts results if the return type is of type {@link Iterator} and the original value is
* {@literal null}.
*
* <p>This adapter runs at the priority of {@literal -350}.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/24/15)
*/
public class NullToIteratorResultAdapter extends AbstractResultAdapter<Iterator> {
public NullToIteratorResultAdapter() {
super(-350);
}
@Override
public boolean accepts(Invocation invocation, Object originalValue) {
return originalValue == null && Iterator.class.equals(invocation.getMethod().getReturnType());
}
@Override
public Iterator adapt(Invocation invocation, Object originalValue) {
return EmptyIterator.INSTANCE;
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/VoidResultAdapter.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/VoidResultAdapter.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.Invocation;
/**
* This adapter is used to adapt any value to the method type of {@literal void} by returning
* {@literal null}.
*
* <p>This adapter is executed at {@link Integer#MIN_VALUE the lowest possible priority}.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/24/15)
*/
public class VoidResultAdapter extends AbstractResultAdapter<Object> {
public VoidResultAdapter() {
super(Integer.MIN_VALUE);
}
@Override
public boolean accepts(Invocation invocation, Object originalValue) {
return void.class.equals(invocation.getMethod().getReturnType());
}
@Override
public Object adapt(Invocation invocation, Object originalValue) {
return null;
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToListenableFutureResultAdapter.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToListenableFutureResultAdapter.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.Invocation;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureTask;
/**
* This adapter will try to adapt a {@literal null} value to a listenable future.
*
* <p>It adapts results if the return type is of type {@link ListenableFuture} and the original
* value is {@literal null}.
*
* <p>This adapter runs at the priority of {@literal -100}.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/28/15)
*/
public class NullToListenableFutureResultAdapter extends AbstractResultAdapter<ListenableFuture> {
public NullToListenableFutureResultAdapter() {
super(-100);
}
@Override
public boolean accepts(Invocation invocation, Object originalValue) {
return originalValue == null
&& invocation.getMethod().getReturnType().equals(ListenableFuture.class);
}
@Override
public ListenableFuture adapt(Invocation invocation, Object originalValue) {
//noinspection unchecked
final ListenableFutureTask task = new ListenableFutureTask(() -> null);
task.run();
return task;
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/AbstractIterableResultAdapter.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/AbstractIterableResultAdapter.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.Invocation;
/**
* This is the base class that provides the basics for adapting results from an iterable object.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/28/15)
*/
public abstract class AbstractIterableResultAdapter<E> extends AbstractResultAdapter<E> {
public AbstractIterableResultAdapter(int priority) {
super(priority);
}
@Override
public E adapt(Invocation invocation, Object originalValue) {
final Iterable iterable = (Iterable) originalValue;
return doAdapt(invocation, iterable);
}
/**
* This is called when we want to adapt an iterable object to another type.
*
* @param invocation the invocation which called for this adaptation
* @param iterable the iterable to be adapted to the appropriate result type
* @return the adapted result
*/
protected abstract E doAdapt(Invocation invocation, Iterable iterable);
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/CollectionIterableResultAdapter.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/CollectionIterableResultAdapter.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.Invocation;
import com.mmnaseri.utils.spring.data.error.ResultAdapterFailureException;
import com.mmnaseri.utils.spring.data.tools.CollectionInstanceUtils;
import java.util.Collection;
/**
* This adapter will adapt results from an iterable to the appropriate collection type. It will
* accept adaptations if the original value is an iterable object and the target result is some sort
* {@link java.util.Collection collection}.
*
* <p>This adapter will execute at priority {@literal -300}.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/28/15)
*/
public class CollectionIterableResultAdapter extends AbstractIterableResultAdapter<Collection> {
public CollectionIterableResultAdapter() {
super(-300);
}
@Override
protected Collection doAdapt(Invocation invocation, Iterable iterable) {
final Collection collection;
try {
collection = CollectionInstanceUtils.getCollection(invocation.getMethod().getReturnType());
} catch (IllegalArgumentException e) {
throw new ResultAdapterFailureException(iterable, invocation.getMethod().getReturnType(), e);
}
for (Object item : iterable) {
//noinspection unchecked
collection.add(item);
}
return collection;
}
@Override
public boolean accepts(Invocation invocation, Object originalValue) {
return originalValue instanceof Iterable
&& Collection.class.isAssignableFrom(invocation.getMethod().getReturnType());
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/regular/ToStringNonDataOperationHandler.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/regular/ToStringNonDataOperationHandler.java | package com.mmnaseri.utils.spring.data.proxy.impl.regular;
import com.mmnaseri.utils.spring.data.proxy.NonDataOperationHandler;
import java.lang.reflect.Method;
import static com.mmnaseri.utils.spring.data.proxy.impl.regular.EqualsNonDataOperationHandler.superInterfaces;
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.toList;
/**
* This class will handle the {@link Object#toString()} method.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/8/16)
*/
public class ToStringNonDataOperationHandler implements NonDataOperationHandler {
private static final String TO_STRING = "toString";
@Override
public boolean handles(Object proxy, Method method, Object... args) {
return Object.class.equals(method.getDeclaringClass()) && TO_STRING.equals(method.getName());
}
@Override
public Object invoke(Object proxy, Method method, Object... args) {
return "mock<" + superInterfaces(proxy.getClass()).sorted(comparing(Class::getCanonicalName)).collect(toList()).toString() + ">";
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/regular/HashCodeNonDataOperationHandler.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/regular/HashCodeNonDataOperationHandler.java | package com.mmnaseri.utils.spring.data.proxy.impl.regular;
import com.google.common.base.Objects;
import com.mmnaseri.utils.spring.data.proxy.NonDataOperationHandler;
import java.lang.reflect.Method;
import java.util.Comparator;
import static com.mmnaseri.utils.spring.data.proxy.impl.regular.EqualsNonDataOperationHandler.superInterfaces;
/**
* This class will handle the {@link Object#hashCode()} method.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/8/16)
*/
public class HashCodeNonDataOperationHandler implements NonDataOperationHandler {
private static final String HASH_CODE = "hashCode";
@Override
public boolean handles(Object proxy, Method method, Object... args) {
return Object.class.equals(method.getDeclaringClass()) && HASH_CODE.equals(method.getName());
}
@Override
public Object invoke(Object proxy, Method method, Object... args) {
return Objects.hashCode(superInterfaces(proxy.getClass()).sorted(Comparator.comparing(Class::getCanonicalName)).toArray());
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/regular/EqualsNonDataOperationHandler.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/regular/EqualsNonDataOperationHandler.java | package com.mmnaseri.utils.spring.data.proxy.impl.regular;
import com.mmnaseri.utils.spring.data.proxy.NonDataOperationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.util.stream.Stream;
import static java.util.Arrays.stream;
import static java.util.stream.Collectors.toSet;
/**
* This class will handle the {@link Object#equals(Object)} method.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/8/16)
*/
public class EqualsNonDataOperationHandler implements NonDataOperationHandler {
private static final String EQUALS = "equals";
@Override
public boolean handles(Object proxy, Method method, Object... args) {
return Object.class.equals(method.getDeclaringClass()) && EQUALS.equals(method.getName());
}
@Override
public Object invoke(Object proxy, Method method, Object... args) {
final Object that = args[0];
if (that == null || !Proxy.isProxyClass(that.getClass())) {
return false;
}
return superInterfaces(proxy.getClass()).collect(toSet()).equals(superInterfaces(that.getClass()).collect(toSet()));
}
static Stream<Class<?>> superInterfaces(Class<?> type) {
return Stream.concat(Stream.of(type), stream(type.getInterfaces()).flatMap(EqualsNonDataOperationHandler::superInterfaces)).filter(item -> Modifier.isInterface(item.getModifiers()));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/regular/InterfaceDefaultMethodNonDataOperation.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/regular/InterfaceDefaultMethodNonDataOperation.java | package com.mmnaseri.utils.spring.data.proxy.impl.regular;
import com.mmnaseri.utils.spring.data.error.DataOperationExecutionException;
import com.mmnaseri.utils.spring.data.proxy.NonDataOperationHandler;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
/**
* An invocation handler that attempts to locate and call an appropriate default method from an interface type.
*/
public class InterfaceDefaultMethodNonDataOperation implements NonDataOperationHandler {
@Override
public boolean handles(Object proxy, Method method, Object... args) {
return method.isDefault();
}
@Override
public Object invoke(Object proxy, Method method, Object... args) {
try {
return callDefaultMethod(new MethodInvocation(proxy, method, args));
} catch (Throwable throwable) {
throw new DataOperationExecutionException("Failed to execute default method " + method, throwable);
}
}
private Object callDefaultMethod(final MethodInvocation invocation) throws Throwable {
try {
return callDefaultMethodWithLookup(defaultLookup(), invocation);
} catch (IllegalAccessException e) {
if (e.getMessage().matches(".*no private access for invokespecial.*")) {
return tryWithAccessibleLookup(invocation);
}
throw e;
}
}
private Object tryWithAccessibleLookup(final MethodInvocation invocation) throws Throwable {
try {
return callDefaultMethodWithLookup(accessibleLookup(invocation), invocation);
} catch (Throwable throwable) {
if (throwable.getClass().getName().equals("java.lang.reflect.InaccessibleObjectException")) {
return tryWithPrivateLookup(invocation);
}
throw throwable;
}
}
private Object tryWithPrivateLookup(final MethodInvocation invocation) throws Throwable {
return callDefaultMethodWithLookup(privateLookup(invocation), invocation);
}
private MethodHandles.Lookup privateLookup(final MethodInvocation invocation)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
Method privateLookupIn =
MethodHandles.class.getDeclaredMethod(
"privateLookupIn", Class.class, MethodHandles.Lookup.class);
return (MethodHandles.Lookup)
privateLookupIn.invoke(
null, invocation.method().getDeclaringClass(), MethodHandles.lookup());
}
private Object callDefaultMethodWithLookup(
MethodHandles.Lookup lookup, MethodInvocation invocation) throws Throwable {
try {
return lookup
.in(invocation.method().getDeclaringClass())
.unreflectSpecial(invocation.method(), invocation.instance().getClass())
.bindTo(invocation.instance())
.invokeWithArguments(invocation.arguments());
} catch (IllegalAccessException exception) {
if (exception.getMessage().contains("no private access for invokespecial")) {
return lookup
.findSpecial(
invocation.method().getDeclaringClass(),
invocation.method().getName(),
MethodType.methodType(
invocation.method().getReturnType(), invocation.method().getParameterTypes()),
invocation.method().getDeclaringClass())
.bindTo(invocation.instance())
.invokeWithArguments(invocation.arguments());
} else {
throw exception;
}
}
}
private static MethodHandles.Lookup defaultLookup() {
return MethodHandles.lookup();
}
private static MethodHandles.Lookup accessibleLookup(MethodInvocation invocation)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException,
InstantiationException {
Constructor<MethodHandles.Lookup> constructor =
MethodHandles.Lookup.class.getDeclaredConstructor(Class.class);
constructor.setAccessible(true);
return constructor.newInstance(invocation.method().getDeclaringClass());
}
private static class MethodInvocation {
private final Object instance;
private final Method method;
private final Object[] arguments;
public MethodInvocation(
final Object instance, final Method method, final Object[] arguments) {
this.instance = instance;
this.arguments = arguments == null ? new Object[0] : Arrays.copyOf(arguments, arguments.length);
this.method = method;
}
public Object instance() {
return instance;
}
public Object[] arguments() {
return Arrays.copyOf(arguments, arguments.length);
}
public Method method() {
return method;
}
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/SignatureDataOperationResolver.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/SignatureDataOperationResolver.java | package com.mmnaseri.utils.spring.data.proxy.impl.resolvers;
import com.mmnaseri.utils.spring.data.domain.impl.MethodInvocationDataStoreOperation;
import com.mmnaseri.utils.spring.data.proxy.DataOperationResolver;
import com.mmnaseri.utils.spring.data.proxy.TypeMapping;
import com.mmnaseri.utils.spring.data.store.DataStoreOperation;
import com.mmnaseri.utils.spring.data.tools.PropertyUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
/**
* This class will resolve methods to the equivalent methods of the mapped implementations.
*
* <p>The process of equating methods to their implementation finds methods on the nearest
* implementation that can handle the given parameters, and whose name is the exact same as the
* invoked method.
*
* <p>Since the return value of the method can and will be adapted to the return value of the
* invoked method, return values are not considered to be so important, and they are not checked or
* considered.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/29/15)
*/
@SuppressWarnings("WeakerAccess")
public class SignatureDataOperationResolver implements DataOperationResolver {
private static final Log log = LogFactory.getLog(SignatureDataOperationResolver.class);
private final List<TypeMapping<?>> mappings;
public SignatureDataOperationResolver(List<TypeMapping<?>> mappings) {
this.mappings = mappings;
}
@Override
public DataStoreOperation<?, ?, ?> resolve(Method method) {
log.info(
"Trying to resolve the data operation for method "
+ method
+ " by going through the previously set up type mappings");
for (TypeMapping<?> mapping : mappings) {
final Class<?> type = mapping.getType();
final Method declaration = findMethod(type, method.getName(), method.getParameterTypes());
if (declaration != null) {
log.info(
"Setting the resolution as a method invocation on the previously prepared type mapping");
final Object instance = mapping.getInstance();
return new MethodInvocationDataStoreOperation<>(instance, declaration);
}
}
return null;
}
private static Method findMethod(Class<?> type, String name, Class<?>... parameterTypes) {
log.debug(
"Attempting to look for the actual declaration of the method named '"
+ name
+ "' with parameter types "
+ Arrays.toString(parameterTypes)
+ " on the child type "
+ type);
Class<?> searchType = type;
while (searchType != null) {
log.trace("Looking at type " + type + " for method " + name);
final Method[] methods =
searchType.isInterface() ? searchType.getMethods() : searchType.getDeclaredMethods();
for (Method method : methods) {
if (method.getName().equals(name)
&& parameterTypes.length == method.getParameterTypes().length) {
boolean matches = true;
for (int i = 0; i < parameterTypes.length; i++) {
final Class<?> parameterType = parameterTypes[i];
if (!PropertyUtils.getTypeOf(method.getParameterTypes()[i])
.isAssignableFrom(PropertyUtils.getTypeOf(parameterType))) {
matches = false;
break;
}
}
if (matches) {
return method;
}
}
}
searchType = searchType.getSuperclass();
}
return null;
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/QueryMethodDataOperationResolver.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/QueryMethodDataOperationResolver.java | package com.mmnaseri.utils.spring.data.proxy.impl.resolvers;
import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata;
import com.mmnaseri.utils.spring.data.domain.impl.DescribedDataStoreOperation;
import com.mmnaseri.utils.spring.data.domain.impl.MethodQueryDescriptionExtractor;
import com.mmnaseri.utils.spring.data.domain.impl.SelectDataStoreOperation;
import com.mmnaseri.utils.spring.data.proxy.DataOperationResolver;
import com.mmnaseri.utils.spring.data.proxy.RepositoryFactoryConfiguration;
import com.mmnaseri.utils.spring.data.query.DataFunctionRegistry;
import com.mmnaseri.utils.spring.data.query.QueryDescriptor;
import com.mmnaseri.utils.spring.data.store.DataStoreOperation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.data.annotation.QueryAnnotation;
import java.lang.reflect.Method;
/**
* This class will resolve methods to their query method equivalent by parsing their names and
* parameters.
*
* <p>Even though, technically speaking, a class annotated with {@link QueryAnnotation} <em>is</em>
* a query method, this class will ignore such methods since it doesn't know how to respond to
* native queries.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/29/15)
*/
@SuppressWarnings("WeakerAccess")
public class QueryMethodDataOperationResolver implements DataOperationResolver {
private static final Log log = LogFactory.getLog(QueryMethodDataOperationResolver.class);
private final MethodQueryDescriptionExtractor descriptionExtractor;
private final RepositoryMetadata repositoryMetadata;
private final DataFunctionRegistry functionRegistry;
private final RepositoryFactoryConfiguration configuration;
public QueryMethodDataOperationResolver(
MethodQueryDescriptionExtractor descriptionExtractor,
RepositoryMetadata repositoryMetadata,
DataFunctionRegistry functionRegistry,
RepositoryFactoryConfiguration configuration) {
this.descriptionExtractor = descriptionExtractor;
this.repositoryMetadata = repositoryMetadata;
this.functionRegistry = functionRegistry;
this.configuration = configuration;
}
@Override
public DataStoreOperation<?, ?, ?> resolve(Method method) {
if (AnnotationUtils.findAnnotation(method, QueryAnnotation.class) != null) {
log.info("Found a @Query annotation on the method " + method);
// we don't know how to handle vendor-specific query methods
return null;
}
log.info("Extracting query description from the method by parsing the method");
final QueryDescriptor descriptor =
descriptionExtractor.extract(repositoryMetadata, configuration, method);
return new DescribedDataStoreOperation<>(
new SelectDataStoreOperation<>(descriptor), functionRegistry);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/DefaultDataOperationResolver.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/DefaultDataOperationResolver.java | package com.mmnaseri.utils.spring.data.proxy.impl.resolvers;
import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata;
import com.mmnaseri.utils.spring.data.domain.impl.MethodQueryDescriptionExtractor;
import com.mmnaseri.utils.spring.data.error.DataOperationDefinitionException;
import com.mmnaseri.utils.spring.data.error.UnknownDataOperationException;
import com.mmnaseri.utils.spring.data.proxy.DataOperationResolver;
import com.mmnaseri.utils.spring.data.proxy.RepositoryFactoryConfiguration;
import com.mmnaseri.utils.spring.data.proxy.TypeMapping;
import com.mmnaseri.utils.spring.data.query.DataFunctionRegistry;
import com.mmnaseri.utils.spring.data.store.DataStoreOperation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
/**
* This class will use the other resolvers to find out how a data operation should be handled.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/29/15)
*/
public class DefaultDataOperationResolver implements DataOperationResolver {
private static final Log log = LogFactory.getLog(DefaultDataOperationResolver.class);
private final List<DataOperationResolver> resolvers;
public DefaultDataOperationResolver(
List<TypeMapping<?>> implementations,
MethodQueryDescriptionExtractor descriptionExtractor,
RepositoryMetadata repositoryMetadata,
DataFunctionRegistry functionRegistry,
RepositoryFactoryConfiguration configuration) {
resolvers = new ArrayList<>();
resolvers.add(new SignatureDataOperationResolver(implementations));
resolvers.add(
new QueryMethodDataOperationResolver(
descriptionExtractor, repositoryMetadata, functionRegistry, configuration));
}
@Override
public DataStoreOperation<?, ?, ?> resolve(Method method) {
log.info("Resolving the data operation for method " + method);
for (DataOperationResolver resolver : resolvers) {
log.debug("Attempting to resolve the method call using resolver " + resolver);
final DataStoreOperation<?, ?, ?> resolution;
try {
resolution = resolver.resolve(method);
} catch (Exception e) {
throw new DataOperationDefinitionException(method, e);
}
if (resolution != null) {
return resolution;
}
}
log.error("No suitable data operation could be found for method " + method);
throw new UnknownDataOperationException(method);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/MultipleIdPropertiesException.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/MultipleIdPropertiesException.java | package com.mmnaseri.utils.spring.data.error;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/8/16)
*/
public class MultipleIdPropertiesException extends EntityDefinitionException {
public MultipleIdPropertiesException(Class<?> entityType) {
super(
"There are multiple properties in "
+ entityType
+ " that are annotated as the ID property");
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/ResultAdapterFailureException.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/ResultAdapterFailureException.java | package com.mmnaseri.utils.spring.data.error;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/8/16)
*/
public class ResultAdapterFailureException extends DataOperationException {
public ResultAdapterFailureException(Object originalValue, Class<?> expectedType) {
super("Could not adapt value: <" + originalValue + "> to type <" + expectedType + ">");
}
public ResultAdapterFailureException(
Object originalValue, Class<?> expectedType, String failure) {
super(
"Could not adapt value: <"
+ originalValue
+ "> to type <"
+ expectedType
+ ">; "
+ failure);
}
public ResultAdapterFailureException(
Object originalValue, Class<?> expectedType, Throwable failure) {
super(
"Could not adapt value: <" + originalValue + "> to type <" + expectedType + ">; ", failure);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/MockBuilderException.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/MockBuilderException.java | package com.mmnaseri.utils.spring.data.error;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/8/16)
*/
public class MockBuilderException extends RepositoryMockException {
public MockBuilderException(String message, Throwable cause) {
super(message, cause);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/EntityMissingKeyException.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/EntityMissingKeyException.java | package com.mmnaseri.utils.spring.data.error;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/8/16)
*/
public class EntityMissingKeyException extends EntityStateException {
public EntityMissingKeyException(Class<?> entityType, String keyProperty) {
super(
"An object of instance "
+ entityType
+ " must declare a valid key under property "
+ keyProperty);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/NoIdPropertyException.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/NoIdPropertyException.java | package com.mmnaseri.utils.spring.data.error;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/8/16)
*/
public class NoIdPropertyException extends EntityDefinitionException {
public NoIdPropertyException(Class<?> entityType) {
super("No id property could be resolved for type " + entityType);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/PropertyTypeMismatchException.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/PropertyTypeMismatchException.java | package com.mmnaseri.utils.spring.data.error;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/8/16)
*/
public class PropertyTypeMismatchException extends EntityDefinitionException {
public PropertyTypeMismatchException(
Class<?> declaringClass, String propertyName, Class<?> expectedType, Class<?> actualType) {
super(
"Expected property <"
+ propertyName
+ "> of class <"
+ declaringClass
+ "> to be of type <"
+ expectedType
+ "> but it was of type <"
+ actualType
+ ">");
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/PrimitiveIdTypeException.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/PrimitiveIdTypeException.java | package com.mmnaseri.utils.spring.data.error;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (6/12/16, 5:58 PM)
*/
public class PrimitiveIdTypeException extends EntityDefinitionException {
public PrimitiveIdTypeException(Class<?> entityType, String idProperty) {
super(
"The ID property ("
+ idProperty
+ ") found on entity <"
+ entityType
+ "> is of a primitive type. Primitive types are not supported by this framework.");
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataOperationException.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataOperationException.java | package com.mmnaseri.utils.spring.data.error;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/8/16)
*/
public abstract class DataOperationException extends RepositoryMockException {
public DataOperationException(String message) {
super(message);
}
public DataOperationException(String message, Throwable cause) {
super(message, cause);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/QueryParserException.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/QueryParserException.java | package com.mmnaseri.utils.spring.data.error;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/8/16)
*/
public class QueryParserException extends RepositoryDefinitionException {
public QueryParserException(Class<?> repositoryInterface, String message) {
super(repositoryInterface, message);
}
public QueryParserException(Class<?> repositoryInterface, String message, Throwable cause) {
super(repositoryInterface, message, cause);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataOperationDefinitionException.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataOperationDefinitionException.java | package com.mmnaseri.utils.spring.data.error;
import java.lang.reflect.Method;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/8/16)
*/
public class DataOperationDefinitionException extends DataOperationException {
public DataOperationDefinitionException(Method method, Throwable cause) {
super("Encountered an error while resolving operation metadata: " + method, cause);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/RepositoryDefinitionException.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/RepositoryDefinitionException.java | package com.mmnaseri.utils.spring.data.error;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/8/16)
*/
public class RepositoryDefinitionException extends RepositoryMockException {
public RepositoryDefinitionException(Class<?> repositoryInterface, String message) {
super(repositoryInterface + ": " + message);
}
public RepositoryDefinitionException(
Class<?> repositoryInterface, String message, Throwable cause) {
super(repositoryInterface + ": " + message, cause);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataStoreException.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataStoreException.java | package com.mmnaseri.utils.spring.data.error;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/8/16)
*/
public class DataStoreException extends RepositoryMockException {
public DataStoreException(Class<?> entityType, String message) {
super(entityType + ": " + message);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/EntityDefinitionException.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/EntityDefinitionException.java | package com.mmnaseri.utils.spring.data.error;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/8/16)
*/
public abstract class EntityDefinitionException extends RepositoryMockException {
public EntityDefinitionException(String message) {
super(message);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DuplicateFunctionException.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DuplicateFunctionException.java | package com.mmnaseri.utils.spring.data.error;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public class DuplicateFunctionException extends FunctionRegistryException {
public DuplicateFunctionException(String name) {
super("Another function with this name has already been registered: " + name);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/ResultConversionFailureException.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/ResultConversionFailureException.java | package com.mmnaseri.utils.spring.data.error;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/8/16)
*/
public class ResultConversionFailureException extends DataOperationException {
public ResultConversionFailureException(Throwable cause) {
super("Failed to retrieve promised result", cause);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/EntityStateException.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/EntityStateException.java | package com.mmnaseri.utils.spring.data.error;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/8/16)
*/
public abstract class EntityStateException extends RepositoryMockException {
public EntityStateException(String message) {
super(message);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataStoreNotFoundException.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataStoreNotFoundException.java | package com.mmnaseri.utils.spring.data.error;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/8/16)
*/
public class DataStoreNotFoundException extends DataStoreException {
public DataStoreNotFoundException(Class<?> entityType) {
super(entityType, "No data store could be found for this entity type: " + entityType);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/FunctionRegistryException.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/FunctionRegistryException.java | package com.mmnaseri.utils.spring.data.error;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public abstract class FunctionRegistryException extends RepositoryMockException {
public FunctionRegistryException(String message) {
super(message);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/OperatorContextException.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/OperatorContextException.java | package com.mmnaseri.utils.spring.data.error;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/8/16)
*/
public class OperatorContextException extends RepositoryMockException {
public OperatorContextException(String message) {
super(message);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataOperationExecutionException.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataOperationExecutionException.java | package com.mmnaseri.utils.spring.data.error;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public class DataOperationExecutionException extends DataOperationException {
public DataOperationExecutionException(String message, Throwable cause) {
super(message, cause);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DuplicateOperatorException.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DuplicateOperatorException.java | package com.mmnaseri.utils.spring.data.error;
import com.mmnaseri.utils.spring.data.domain.Operator;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/8/16)
*/
public class DuplicateOperatorException extends OperatorContextException {
public DuplicateOperatorException(Operator existing, String token) {
super(
"Another operator ("
+ existing.getName()
+ ") already defines answers to this token: "
+ token);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/CorruptDataException.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/CorruptDataException.java | package com.mmnaseri.utils.spring.data.error;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/8/16)
*/
public class CorruptDataException extends DataStoreException {
public CorruptDataException(Class<?> entityType, Object data, String corruption) {
super(entityType, entityType + ": Data <" + data + "> is unacceptable. " + corruption);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataFunctionException.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataFunctionException.java | package com.mmnaseri.utils.spring.data.error;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/8/16)
*/
public class DataFunctionException extends DataOperationException {
public DataFunctionException(String message) {
super(message);
}
public DataFunctionException(String message, Throwable cause) {
super(message, cause);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/InvalidArgumentException.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/InvalidArgumentException.java | package com.mmnaseri.utils.spring.data.error;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/8/16)
*/
public class InvalidArgumentException extends DataOperationException {
public InvalidArgumentException(String message) {
super(message);
}
public InvalidArgumentException(String message, Throwable cause) {
super(message, cause);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/ParserException.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/ParserException.java | package com.mmnaseri.utils.spring.data.error;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/8/16)
*/
public class ParserException extends RuntimeException {
public ParserException(String message) {
super(message);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/UnknownDataOperationException.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/UnknownDataOperationException.java | package com.mmnaseri.utils.spring.data.error;
import java.lang.reflect.Method;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/8/16)
*/
public class UnknownDataOperationException extends DataOperationException {
public UnknownDataOperationException(Method method) {
super("Failed to resolve operation for method: " + method);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/FunctionNotFoundException.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/FunctionNotFoundException.java | package com.mmnaseri.utils.spring.data.error;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/8/16)
*/
public class FunctionNotFoundException extends FunctionRegistryException {
public FunctionNotFoundException(String functionName) {
super("No function with this name has been registered: " + functionName);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/RepositoryMockException.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/RepositoryMockException.java | package com.mmnaseri.utils.spring.data.error;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/8/16)
*/
public abstract class RepositoryMockException extends RuntimeException {
public RepositoryMockException(String message) {
super(message);
}
public RepositoryMockException(String message, Throwable cause) {
super(message, cause);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreOperation.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreOperation.java | package com.mmnaseri.utils.spring.data.store;
import com.mmnaseri.utils.spring.data.domain.Invocation;
import com.mmnaseri.utils.spring.data.proxy.RepositoryConfiguration;
/**
* This interface encapsulates a single operation taking place on a data store
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/17/15)
*/
public interface DataStoreOperation<R, K, E> {
/**
* Called to trigger the actual operation
*
* @param store the data store on which this operation is taking place
* @param configuration the configuration for the data store
* @param invocation the invocation that triggered this operation
* @return the result of the operation
*/
R execute(DataStore<K, E> store, RepositoryConfiguration configuration, Invocation invocation);
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreEventListenerContext.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreEventListenerContext.java | package com.mmnaseri.utils.spring.data.store;
import java.util.List;
/**
* This interface is used to manage events related to a data store
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/12/15)
*/
public interface DataStoreEventListenerContext {
/**
* Registers a new listener
*
* @param listener the listener
* @param <E> the type of events to which the listener wants to subscribe
*/
<E extends DataStoreEvent> void register(DataStoreEventListener<E> listener);
/**
* Triggers an event on the context
*
* @param event the event
*/
void trigger(DataStoreEvent event);
/**
* Returns a list of all event listeners that would be triggered by an event of the given type
* through this context
*
* @param eventType the event type
* @param <E> the event type
* @return a list of listeners in the order in which they would be called
*/
<E extends DataStoreEvent> List<DataStoreEventListener<? extends E>> getListeners(
Class<E> eventType);
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStore.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStore.java | package com.mmnaseri.utils.spring.data.store;
import java.util.Collection;
/**
* This interface encapsulates the abstract data store, with the bare minimum capabilities assumed.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/17/15)
*/
public interface DataStore<K, E> {
/**
* Determines whether or not an entity with the given key exists in the data store.
*
* @param key the key
* @return {@literal boolean} if such a key is known by the data store
*/
boolean hasKey(K key);
/**
* Saves the given entity into the data store under the provided key. Whether or not the key is
* actually used by the data store in some sort of mapping does not matter. The only expectation
* is that after this call, should the save be successful a call to {@link #hasKey(Object)} should
* yield {@literal true} and the very same entity (or an equal value entity) can be retrieved by
* calling {@link #retrieve(Object)}.
*
* @param key the key
* @param entity the entity
* @return {@literal true} to indicate the entity was a new entry, and {@literal false} to
* indicate another entity had to be replaced/updated with the provided entity
*/
boolean save(K key, E entity);
/**
* Deletes the entity identifiable with the provided key, or does nothing if no such entity
* exists. It is expected that as a side effect, once this method returns successfully, {@link
* #hasKey(Object)} should return {@literal false} and {@link #retrieve(Object)} should return
* {@literal null} for the same key.
*
* @param key the key for which the removal should happen
* @return {@literal true} to indicate the entity was located and removed and {@literal false} to
* indicate that no such entity existed in the first place.
*/
boolean delete(K key);
/**
* Given a key, retrieves the entity associated with that key in the data store.
*
* @param key the key
* @return the entity or {@literal null} if no such entity could be found
*/
E retrieve(K key);
/** @return a collection of all the keys registered in the data store. */
Collection<K> keys();
/** @return retrieves all the entities in the data store */
Collection<E> retrieveAll();
/** @return the entity type bound to this data store */
Class<E> getEntityType();
/** Does a hard remove of all the entities in the data store */
void truncate();
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreEventPublisher.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreEventPublisher.java | package com.mmnaseri.utils.spring.data.store;
/**
* This interface abstracts the process of publishing a data store event
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/6/15)
*/
@SuppressWarnings("unused")
public interface DataStoreEventPublisher {
/**
* This method is called to publish a data store event
*
* @param event the event that should be published
*/
void publishEvent(DataStoreEvent event);
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreEventListener.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreEventListener.java | package com.mmnaseri.utils.spring.data.store;
/**
* This interface encapsulates the task of listening to and reacting to an event
*
* @param <E> the type of the event to which this listener subscribes
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/6/15)
*/
public interface DataStoreEventListener<E extends DataStoreEvent> {
/**
* Will be called by the data store when a relevant event happens
*
* @param event the event that has taken place
*/
void onEvent(E event);
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreEvent.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreEvent.java | package com.mmnaseri.utils.spring.data.store;
import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata;
/**
* This interface indicates that a data store operation was requested or completed.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/6/15)
*/
public interface DataStoreEvent {
/** @return the repository metadata associated with the given data store */
RepositoryMetadata getRepositoryMetadata();
/** @return the data store that triggered this event */
DataStore<?, ?> getDataStore();
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreRegistry.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreRegistry.java | package com.mmnaseri.utils.spring.data.store;
/**
* This interface is used to register and look up data store for specific entity types.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/29/15)
*/
public interface DataStoreRegistry {
/**
* Registers a new data store. Note that you can override an existing data store for an entity by
* registering another one that supports the same sort of entity.
*
* @param dataStore the data store
* @param <E> the type of the entities
* @param <K> the type of the keys
*/
<E, K> void register(DataStore<K, E> dataStore);
/**
* Finds the data store for the given entity type
*
* @param entityType the entity type
* @param <E> the type of the entities
* @param <K> the type of the keys
* @return the data store that can handle the provided type of entity
* @throws com.mmnaseri.utils.spring.data.error.DataStoreNotFoundException if no data store can be
* found for the given entity type
*/
<E, K> DataStore<K, E> getDataStore(Class<E> entityType);
/**
* Used to determine whether or not a data store has been registered that supports the given
* entity type.
*
* @param entityType the entity type
* @return {@literal true} to indicate that the entity type has a corresponding data store in this
* registry
*/
boolean has(Class<?> entityType);
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/QueueingDataStore.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/QueueingDataStore.java | package com.mmnaseri.utils.spring.data.store;
/**
* This interface indicates that the implementing data store has queueing capabilities and can thus
* be called upon to flush the queue and commit the results, and more over, handle operations in
* batches by refraining to flush the queue automatically while a batch is in progress.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/11/16, 1:18 PM)
*/
public interface QueueingDataStore<K, E, B> extends DataStore<K, E> {
/** Should be called to manually trigger a flush */
void flush();
/**
* Starts a batch
*
* @return returns a key that can be used to identify this batch and {@link #endBatch(Object) end
* it}
*/
B startBatch();
/**
* Ends the indicated batch. Note that ending the batch does not necessarily flush the queue if
* the threshold for the underlying data store has not been reached.
*
* @param batch the batch to end
*/
void endBatch(B batch);
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/DefaultDataStoreRegistry.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/DefaultDataStoreRegistry.java | package com.mmnaseri.utils.spring.data.store.impl;
import com.mmnaseri.utils.spring.data.error.DataStoreNotFoundException;
import com.mmnaseri.utils.spring.data.store.DataStore;
import com.mmnaseri.utils.spring.data.store.DataStoreRegistry;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* This is the default implementation of the data store registry that supports caching a data store
* based on the type of entity the data store supports.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/29/15)
*/
public class DefaultDataStoreRegistry implements DataStoreRegistry {
private static final Log log = LogFactory.getLog(DefaultDataStoreRegistry.class);
private final Map<Class<?>, DataStore<?, ?>> dataStores = new ConcurrentHashMap<>();
@Override
public <E, K> void register(DataStore<K, E> dataStore) {
log.info("Registering a data store for type " + dataStore.getEntityType());
dataStores.put(dataStore.getEntityType(), dataStore);
}
@Override
public <E, K> DataStore<K, E> getDataStore(Class<E> entityType) {
if (!dataStores.containsKey(entityType)) {
log.error("There is no data store registered for entity type " + entityType);
log.debug("Registered data types are " + dataStores.keySet());
throw new DataStoreNotFoundException(entityType);
}
//noinspection unchecked
return (DataStore<K, E>) dataStores.get(entityType);
}
@Override
public boolean has(Class<?> entityType) {
return dataStores.containsKey(entityType);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/BeforeUpdateDataStoreEvent.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/BeforeUpdateDataStoreEvent.java | package com.mmnaseri.utils.spring.data.store.impl;
import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata;
import com.mmnaseri.utils.spring.data.store.DataStore;
/**
* This event indicates that an entity is scheduled to be updated.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/6/15)
*/
@SuppressWarnings("WeakerAccess")
public class BeforeUpdateDataStoreEvent extends AbstractEntityDataStoreEvent {
public BeforeUpdateDataStoreEvent(
RepositoryMetadata repositoryMetadata, DataStore<?, ?> dataStore, Object entity) {
super(repositoryMetadata, dataStore, entity);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AuditDataEventListener.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AuditDataEventListener.java | package com.mmnaseri.utils.spring.data.store.impl;
import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata;
import com.mmnaseri.utils.spring.data.store.DataStoreEvent;
import com.mmnaseri.utils.spring.data.store.DataStoreEventListener;
import org.springframework.data.domain.Auditable;
import org.springframework.data.domain.AuditorAware;
import java.time.Instant;
/**
* This event listener can be registered with an {@link
* com.mmnaseri.utils.spring.data.store.DataStoreEventListenerContext event listener context} to add
* support for auditing entities as per the specifications set forth by Spring Data Commons.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/12/15)
*/
public class AuditDataEventListener implements DataStoreEventListener<DataStoreEvent> {
private final AuditorAware auditorAware;
public AuditDataEventListener(AuditorAware auditorAware) {
this.auditorAware = auditorAware;
}
@SuppressWarnings({"unchecked", "ConstantConditions"})
@Override
public void onEvent(DataStoreEvent event) {
if (event instanceof BeforeInsertDataStoreEvent) {
final Object entity = ((BeforeInsertDataStoreEvent) event).getEntity();
final Auditable wrapper = getAuditable(entity, event.getRepositoryMetadata());
wrapper.setCreatedBy(
auditorAware == null ? null : auditorAware.getCurrentAuditor().orElse(null));
wrapper.setCreatedDate(Instant.now());
} else if (event instanceof BeforeUpdateDataStoreEvent) {
final Object entity = ((BeforeUpdateDataStoreEvent) event).getEntity();
final Auditable wrapper = getAuditable(entity, event.getRepositoryMetadata());
wrapper.setLastModifiedBy(
auditorAware == null ? null : auditorAware.getCurrentAuditor().orElse(null));
wrapper.setLastModifiedDate(Instant.now());
}
}
/**
* @return the auditor aware that is being used by this listener for setting auditor related
* properties
*/
public AuditorAware getAuditorAware() {
return auditorAware;
}
/**
* Given an entity returns an {@link Auditable} for it. If the entity itself implements that
* interface, it will be returned without any changes, otherwise it will be wrapped in an {@link
* AuditableWrapper}.
*
* @param entity the entity
* @param repositoryMetadata the repository metadata for the entity
* @return the auditable entity
*/
private static Auditable getAuditable(Object entity, RepositoryMetadata repositoryMetadata) {
if (entity instanceof Auditable) {
return (Auditable) entity;
} else {
return new AuditableWrapper(entity, repositoryMetadata);
}
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/EventPublishingDataStore.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/EventPublishingDataStore.java | package com.mmnaseri.utils.spring.data.store.impl;
import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata;
import com.mmnaseri.utils.spring.data.error.CorruptDataException;
import com.mmnaseri.utils.spring.data.store.DataStore;
import com.mmnaseri.utils.spring.data.store.DataStoreEvent;
import com.mmnaseri.utils.spring.data.store.DataStoreEventListenerContext;
import com.mmnaseri.utils.spring.data.store.DataStoreEventPublisher;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.Collection;
/**
* This implementation relies on a delegate data store to handling the actual storage/retrieval. It
* decorates the delegate with event triggering capabilities and some additional data integrity
* checks (null checking).
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/6/15)
*/
public class EventPublishingDataStore<K, E> implements DataStore<K, E>, DataStoreEventPublisher {
private static final Log log = LogFactory.getLog(EventPublishingDataStore.class);
private final DataStore<K, E> delegate;
private final RepositoryMetadata repositoryMetadata;
private final DataStoreEventListenerContext listenerContext;
public EventPublishingDataStore(
DataStore<K, E> delegate,
RepositoryMetadata repositoryMetadata,
DataStoreEventListenerContext listenerContext) {
this.delegate = delegate;
this.repositoryMetadata = repositoryMetadata;
this.listenerContext = listenerContext;
}
@Override
public boolean hasKey(K key) {
return delegate.hasKey(key);
}
@Override
public boolean save(K key, E entity) {
if (key == null) {
log.error("Cannot save an entity under a null key");
throw new CorruptDataException(
getEntityType(), null, "Cannot save an entity with a null key");
}
if (entity == null) {
log.error("Cannot save a null value into the data store");
throw new CorruptDataException(getEntityType(), null, "Cannot save null into the data store");
}
final boolean entityIsNew = !delegate.hasKey(key);
if (entityIsNew) {
log.info("About to insert a new entity in the data store under key " + key);
publishEvent(new BeforeInsertDataStoreEvent(repositoryMetadata, this, entity));
} else {
log.info("About to update the entity in the data store under key " + key);
publishEvent(new BeforeUpdateDataStoreEvent(repositoryMetadata, this, entity));
}
delegate.save(key, entity);
if (entityIsNew) {
log.info("Finished inserting the entity in the data store under key " + key);
publishEvent(new AfterInsertDataStoreEvent(repositoryMetadata, this, entity));
return true;
} else {
log.info("Finished updating the entity under key " + key);
publishEvent(new AfterUpdateDataStoreEvent(repositoryMetadata, this, entity));
return false;
}
}
@Override
public boolean delete(K key) {
if (!delegate.hasKey(key)) {
log.info("Attempted to delete entity with key " + key + " but found nothing");
return false;
}
final E entity = delegate.retrieve(key);
log.info("About to delete an entity with key " + key);
publishEvent(new BeforeDeleteDataStoreEvent(repositoryMetadata, this, entity));
delegate.delete(key);
log.info("Finished deleting the entity with key " + key);
publishEvent(new AfterDeleteDataStoreEvent(repositoryMetadata, this, entity));
return true;
}
@Override
public E retrieve(K key) {
return delegate.retrieve(key);
}
@Override
public Collection<K> keys() {
return delegate.keys();
}
@Override
public Collection<E> retrieveAll() {
return delegate.retrieveAll();
}
@Override
public Class<E> getEntityType() {
return delegate.getEntityType();
}
@Override
public void truncate() {
delegate.truncate();
}
@Override
public void publishEvent(DataStoreEvent event) {
listenerContext.trigger(event);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AfterInsertDataStoreEvent.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AfterInsertDataStoreEvent.java | package com.mmnaseri.utils.spring.data.store.impl;
import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata;
import com.mmnaseri.utils.spring.data.store.DataStore;
/**
* This class indicates that an entity was successfully inserted into a data store.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/6/15)
*/
@SuppressWarnings("WeakerAccess")
public class AfterInsertDataStoreEvent extends AbstractEntityDataStoreEvent {
public AfterInsertDataStoreEvent(
RepositoryMetadata repositoryMetadata, DataStore<?, ?> dataStore, Object entity) {
super(repositoryMetadata, dataStore, entity);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AfterDeleteDataStoreEvent.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AfterDeleteDataStoreEvent.java | package com.mmnaseri.utils.spring.data.store.impl;
import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata;
import com.mmnaseri.utils.spring.data.store.DataStore;
/**
* This class indicates that an entity has been successfully deleted from the data store.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/6/15)
*/
@SuppressWarnings("WeakerAccess")
public class AfterDeleteDataStoreEvent extends AbstractEntityDataStoreEvent {
public AfterDeleteDataStoreEvent(
RepositoryMetadata repositoryMetadata, DataStore<?, ?> dataStore, Object entity) {
super(repositoryMetadata, dataStore, entity);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AbstractDataStoreEvent.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AbstractDataStoreEvent.java | package com.mmnaseri.utils.spring.data.store.impl;
import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata;
import com.mmnaseri.utils.spring.data.store.DataStore;
import com.mmnaseri.utils.spring.data.store.DataStoreEvent;
/**
* This base class sets up the grounds for defining data store events
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/6/15)
*/
@SuppressWarnings("WeakerAccess")
public abstract class AbstractDataStoreEvent implements DataStoreEvent {
private final RepositoryMetadata repositoryMetadata;
private final DataStore<?, ?> dataStore;
public AbstractDataStoreEvent(RepositoryMetadata repositoryMetadata, DataStore<?, ?> dataStore) {
this.repositoryMetadata = repositoryMetadata;
this.dataStore = dataStore;
}
@Override
public RepositoryMetadata getRepositoryMetadata() {
return repositoryMetadata;
}
@Override
public DataStore<?, ?> getDataStore() {
return dataStore;
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/DefaultDataStoreEventListenerContext.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/DefaultDataStoreEventListenerContext.java | package com.mmnaseri.utils.spring.data.store.impl;
import com.mmnaseri.utils.spring.data.error.InvalidArgumentException;
import com.mmnaseri.utils.spring.data.store.DataStoreEvent;
import com.mmnaseri.utils.spring.data.store.DataStoreEventListener;
import com.mmnaseri.utils.spring.data.store.DataStoreEventListenerContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* This is the default implementation for the {@link DataStoreEventListenerContext} interface. This
* implementation comes with support for parent context lookup, meaning that you can register event
* listeners with another context, set that as the parent for this context, and have appropriate
* events triggered in that context as well.
*
* <p>It should be noted that listeners registered in the current context always take precedence
* over the listeners found on a possible parent context.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/12/15)
*/
public class DefaultDataStoreEventListenerContext implements DataStoreEventListenerContext {
private static final Log log = LogFactory.getLog(DefaultDataStoreEventListenerContext.class);
private final ConcurrentMap<Class<? extends DataStoreEvent>, List<DataStoreEventListener<?>>>
listeners;
private final DataStoreEventListenerContext parent;
public DefaultDataStoreEventListenerContext() {
this(null);
}
public DefaultDataStoreEventListenerContext(DataStoreEventListenerContext parent) {
this.parent = parent;
listeners = new ConcurrentHashMap<>();
}
@Override
public <E extends DataStoreEvent> void register(DataStoreEventListener<E> listener) {
final SmartDataStoreEventListener<E> eventListener =
new SmartDataStoreEventListener<>(listener);
listeners.putIfAbsent(eventListener.getEventType(), new CopyOnWriteArrayList<>());
log.info("Registering an event listener for type " + eventListener.getEventType());
listeners.get(eventListener.getEventType()).add(eventListener);
}
@Override
public void trigger(DataStoreEvent event) {
if (event == null) {
log.error("The data store event that was triggered was a null value");
throw new InvalidArgumentException("Cannot raise a null event");
}
log.info("Triggering data store event of type " + event.getClass());
for (Class<? extends DataStoreEvent> eventType : listeners.keySet()) {
if (eventType.isInstance(event)) {
for (DataStoreEventListener listener : listeners.get(eventType)) {
log.debug(
"Triggering event on listener "
+ ((SmartDataStoreEventListener) listener).getDelegate());
//noinspection unchecked
listener.onEvent(event);
}
}
}
if (parent != null) {
log.info("Going to trigger the same event on the parent context");
parent.trigger(event);
}
}
@Override
public <E extends DataStoreEvent> List<DataStoreEventListener<? extends E>> getListeners(
Class<E> eventType) {
final List<DataStoreEventListener<? extends E>> found = new LinkedList<>();
for (Class<? extends DataStoreEvent> supportedType : listeners.keySet()) {
if (supportedType.isAssignableFrom(eventType)) {
for (DataStoreEventListener listener : listeners.get(supportedType)) {
//noinspection unchecked
found.add(((SmartDataStoreEventListener) listener).getDelegate());
}
}
}
if (parent != null) {
found.addAll(parent.getListeners(eventType));
}
return found;
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/SmartDataStoreEventListener.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/SmartDataStoreEventListener.java | package com.mmnaseri.utils.spring.data.store.impl;
import com.mmnaseri.utils.spring.data.store.DataStoreEvent;
import com.mmnaseri.utils.spring.data.store.DataStoreEventListener;
import org.springframework.core.GenericTypeResolver;
/**
* This implementation of the data store event listener wraps a given delegate listener and reads
* the supported event type from the generic type arguments on the original listener. This lets us
* interact with the listener without having to read its generic type arguments every time.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/6/15)
*/
@SuppressWarnings("WeakerAccess")
public class SmartDataStoreEventListener<E extends DataStoreEvent>
implements DataStoreEventListener<E> {
private final DataStoreEventListener<E> delegate;
private final Class<E> eventType;
public SmartDataStoreEventListener(DataStoreEventListener<E> delegate) {
this.delegate = delegate;
//noinspection unchecked
eventType =
(Class<E>)
GenericTypeResolver.resolveTypeArgument(
delegate.getClass(), DataStoreEventListener.class);
}
@Override
public void onEvent(E event) {
delegate.onEvent(event);
}
public Class<E> getEventType() {
return eventType;
}
public DataStoreEventListener<E> getDelegate() {
return delegate;
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AfterUpdateDataStoreEvent.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AfterUpdateDataStoreEvent.java | package com.mmnaseri.utils.spring.data.store.impl;
import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata;
import com.mmnaseri.utils.spring.data.store.DataStore;
/**
* This class indicates that an entity was successfully updated in the data store
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/6/15)
*/
@SuppressWarnings("WeakerAccess")
public class AfterUpdateDataStoreEvent extends AbstractEntityDataStoreEvent {
public AfterUpdateDataStoreEvent(
RepositoryMetadata repositoryMetadata, DataStore<?, ?> dataStore, Object entity) {
super(repositoryMetadata, dataStore, entity);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/PropertyVisitor.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/PropertyVisitor.java | package com.mmnaseri.utils.spring.data.store.impl;
import com.mmnaseri.utils.spring.data.tools.PropertyUtils;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.ReflectionUtils;
import javax.annotation.Nonnull;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* This property visitor will visit all properties (fields and getter methods) to find out the
* property that has the specified annotation. The property can later be retrieved by calling {@link
* #getProperty()}.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/12/15)
*/
class PropertyVisitor implements ReflectionUtils.MethodCallback, ReflectionUtils.FieldCallback {
private final Class<? extends Annotation> annotationType;
private String property;
PropertyVisitor(Class<? extends Annotation> annotationType) {
this.annotationType = annotationType;
}
@Override
public void doWith(@Nonnull Method method) throws IllegalArgumentException {
if (property != null) {
return;
}
if (AnnotationUtils.findAnnotation(method, annotationType) != null) {
property = PropertyUtils.getPropertyName(method);
}
}
@Override
public void doWith(@Nonnull Field field) throws IllegalArgumentException {
if (property != null) {
return;
}
if (field.isAnnotationPresent(annotationType)) {
property = field.getName();
}
}
public String getProperty() {
return property;
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/BeforeDeleteDataStoreEvent.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/BeforeDeleteDataStoreEvent.java | package com.mmnaseri.utils.spring.data.store.impl;
import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata;
import com.mmnaseri.utils.spring.data.store.DataStore;
/**
* This event indicates that an entity is scheduled to be deleted.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/6/15)
*/
@SuppressWarnings("WeakerAccess")
public class BeforeDeleteDataStoreEvent extends AbstractEntityDataStoreEvent {
public BeforeDeleteDataStoreEvent(
RepositoryMetadata repositoryMetadata, DataStore<?, ?> dataStore, Object entity) {
super(repositoryMetadata, dataStore, entity);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/MemoryDataStore.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/MemoryDataStore.java | package com.mmnaseri.utils.spring.data.store.impl;
import com.mmnaseri.utils.spring.data.error.DataStoreException;
import com.mmnaseri.utils.spring.data.store.DataStore;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.Collection;
import java.util.LinkedList;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* This is the default, most basic implementation provided for a data store that stores entities in
* an in-memory {@link java.util.Map map} by mapping entity keys to entities.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/17/15)
*/
public class MemoryDataStore<K, E> implements DataStore<K, E> {
private static final Log log = LogFactory.getLog(MemoryDataStore.class);
private final ConcurrentMap<K, E> store = new ConcurrentHashMap<>();
private final Class<E> entityType;
public MemoryDataStore(Class<E> entityType) {
this.entityType = entityType;
}
@Override
public boolean hasKey(K key) {
log.info("Looking for an object with key " + key);
return store.containsKey(key);
}
@Override
public boolean save(K key, E entity) {
if (key == null) {
log.error("Asked to save an entity with a null key");
throw new DataStoreException(entityType, "Cannot save an entity with a null key");
} else if (entity == null) {
log.error("Asked to save a null value into the data store");
throw new DataStoreException(entityType, "Cannot save a null entity");
}
log.info("Attempting to save entity with key " + key);
boolean saved = store.put(key, entity) == null;
log.debug("Entity was " + (!saved ? "not " : "") + "saved under key " + key);
return saved;
}
@Override
public boolean delete(K key) {
if (key == null) {
log.error("Asked to delete an entity with a null key for reference");
throw new DataStoreException(entityType, "Cannot delete an entity with a null key");
}
if (store.containsKey(key)) {
log.info("Deleting entity under key " + key);
store.remove(key);
return true;
} else {
log.info("No entity was found to delete under key " + key);
}
return false;
}
@Override
public E retrieve(K key) {
if (key == null) {
log.error("Asked to retrieve an entity from a null key");
throw new DataStoreException(entityType, "Cannot retrieve an entity with a null key");
}
if (store.containsKey(key)) {
log.info("Retrieving entity from key " + key);
return store.get(key);
} else {
log.info("No entity was found to return under key " + key);
}
return null;
}
@Override
public Collection<K> keys() {
return new LinkedList<>(store.keySet());
}
@Override
public synchronized Collection<E> retrieveAll() {
log.info("Retrieving all entities from the data store");
return new LinkedList<>(store.values());
}
@Override
public Class<E> getEntityType() {
return entityType;
}
@Override
public void truncate() {
store.clear();
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AbstractEntityDataStoreEvent.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AbstractEntityDataStoreEvent.java | package com.mmnaseri.utils.spring.data.store.impl;
import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata;
import com.mmnaseri.utils.spring.data.store.DataStore;
/**
* This class is the base class for any data store event that indicates a particular entity was
* involved in the event.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/6/15)
*/
@SuppressWarnings("WeakerAccess")
public abstract class AbstractEntityDataStoreEvent extends AbstractDataStoreEvent {
private final Object entity;
public AbstractEntityDataStoreEvent(
RepositoryMetadata repositoryMetadata, DataStore<?, ?> dataStore, Object entity) {
super(repositoryMetadata, dataStore);
this.entity = entity;
}
public Object getEntity() {
return entity;
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/BeforeInsertDataStoreEvent.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/BeforeInsertDataStoreEvent.java | package com.mmnaseri.utils.spring.data.store.impl;
import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata;
import com.mmnaseri.utils.spring.data.store.DataStore;
/**
* This event indicates that an entity is scheduled to be inserted.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/6/15)
*/
@SuppressWarnings("WeakerAccess")
public class BeforeInsertDataStoreEvent extends AbstractEntityDataStoreEvent {
public BeforeInsertDataStoreEvent(
RepositoryMetadata repositoryMetadata, DataStore<?, ?> dataStore, Object entity) {
super(repositoryMetadata, dataStore, entity);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AuditableWrapper.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AuditableWrapper.java | package com.mmnaseri.utils.spring.data.store.impl;
import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata;
import com.mmnaseri.utils.spring.data.tools.GetterMethodFilter;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.domain.Auditable;
import org.springframework.util.ReflectionUtils;
import javax.annotation.Nonnull;
import java.beans.PropertyDescriptor;
import java.lang.annotation.Annotation;
import java.time.Instant;
import java.time.temporal.TemporalAccessor;
import java.util.Date;
import java.util.Optional;
/**
* This class is used to wrap a normal entity in an entity that supports {@link Auditable auditing}.
* If the underlying entity does not exhibit auditable behavior (either by implementing {@link
* Auditable} or by having properties that are annotated with one of the audit annotations provided
* by Spring Data Commons) this class will simply ignore audit requests. Otherwise, it will convert
* the values to their appropriate types and sets and gets the appropriate properties.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/12/15)
*/
@SuppressWarnings("WeakerAccess")
public class AuditableWrapper implements Auditable {
private final BeanWrapper wrapper;
private final RepositoryMetadata repositoryMetadata;
private final String createdBy;
private final String createdDate;
private final String lastModifiedBy;
private final String lastModifiedDate;
public AuditableWrapper(Object entity, RepositoryMetadata repositoryMetadata) {
this.repositoryMetadata = repositoryMetadata;
this.wrapper = new BeanWrapperImpl(entity);
this.createdBy = findProperty(repositoryMetadata.getEntityType(), CreatedBy.class);
this.createdDate = findProperty(repositoryMetadata.getEntityType(), CreatedDate.class);
this.lastModifiedBy = findProperty(repositoryMetadata.getEntityType(), LastModifiedBy.class);
this.lastModifiedDate =
findProperty(repositoryMetadata.getEntityType(), LastModifiedDate.class);
}
@Override
@Nonnull
public Optional<Object> getCreatedBy() {
return Optional.ofNullable(getProperty(Object.class, wrapper, createdBy));
}
@Override
public void setCreatedBy(@Nonnull Object createdBy) {
setProperty(wrapper, this.createdBy, createdBy);
}
@Override
@Nonnull
public Optional<Instant> getCreatedDate() {
return Optional.ofNullable(getProperty(Instant.class, wrapper, createdDate));
}
@Override
public void setCreatedDate(@Nonnull TemporalAccessor creationDate) {
setProperty(wrapper, createdDate, creationDate);
}
@Override
@Nonnull
public Optional<Object> getLastModifiedBy() {
return Optional.ofNullable(getProperty(Object.class, wrapper, lastModifiedBy));
}
@Override
public void setLastModifiedBy(@Nonnull Object lastModifiedBy) {
setProperty(wrapper, this.lastModifiedBy, lastModifiedBy);
}
@Override
@Nonnull
public Optional<Instant> getLastModifiedDate() {
return Optional.ofNullable(getProperty(Instant.class, wrapper, lastModifiedDate));
}
@Override
public void setLastModifiedDate(@Nonnull TemporalAccessor lastModifiedDate) {
setProperty(wrapper, this.lastModifiedDate, lastModifiedDate);
}
@Override
public Object getId() {
return wrapper.getPropertyValue(repositoryMetadata.getIdentifierProperty());
}
@Override
public boolean isNew() {
return getId() == null;
}
private static String findProperty(
Class<?> entityType, Class<? extends Annotation> annotationType) {
final PropertyVisitor visitor = new PropertyVisitor(annotationType);
ReflectionUtils.doWithFields(entityType, visitor);
ReflectionUtils.doWithMethods(entityType, visitor, new GetterMethodFilter());
return visitor.getProperty();
}
/**
* Returns the property value for a given audit property.
*
* @param type the type of the property
* @param wrapper the bean wrapper
* @param property actual property to read
* @param <E> the object type for the value
* @return the property value
*/
private static <E> E getProperty(Class<E> type, BeanWrapper wrapper, String property) {
if (property == null || !wrapper.isReadableProperty(property)) {
return null;
}
Object propertyValue = wrapper.getPropertyValue(property);
if (propertyValue instanceof Date) {
propertyValue = Instant.ofEpochMilli(((Date) propertyValue).getTime());
}
return type.cast(propertyValue);
}
/**
* Sets an audit property on the given entity
*
* @param wrapper the bean wrapper for the entity
* @param property the property for which the value is being set
* @param value the original value of the property
*/
private static void setProperty(BeanWrapper wrapper, String property, Object value) {
if (property != null) {
Object targetValue = value;
final PropertyDescriptor descriptor = wrapper.getPropertyDescriptor(property);
if (targetValue instanceof Instant) {
Instant instant = (Instant) targetValue;
if (Date.class.equals(descriptor.getPropertyType())) {
targetValue = new Date(instant.toEpochMilli());
} else if (java.sql.Date.class.equals(descriptor.getPropertyType())) {
targetValue = new java.sql.Date(instant.toEpochMilli());
} else if (java.sql.Timestamp.class.equals(descriptor.getPropertyType())) {
targetValue = new java.sql.Timestamp(instant.toEpochMilli());
} else if (java.sql.Time.class.equals(descriptor.getPropertyType())) {
targetValue = new java.sql.Time(instant.toEpochMilli());
}
}
if (wrapper.isWritableProperty(property)) {
wrapper.setPropertyValue(property, targetValue);
}
}
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/Configuration.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/Configuration.java | package com.mmnaseri.utils.spring.data.dsl.mock;
import com.mmnaseri.utils.spring.data.proxy.RepositoryFactoryConfiguration;
/**
* Lets us configure the underlying factory using a configuration object
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/14/15)
*/
@SuppressWarnings("WeakerAccess")
public interface Configuration {
/**
* Tells the builder to use the given configuration
*
* @param configuration the configuration
* @return the rest of the configuration
*/
KeyGeneration useConfiguration(RepositoryFactoryConfiguration configuration);
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/Start.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/Start.java | package com.mmnaseri.utils.spring.data.dsl.mock;
/**
* Starting point for the DSL. From this point, you can either specify a factory or a configuration.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/14/15)
*/
@SuppressWarnings("WeakerAccess")
public interface Start extends Factory, Configuration {}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/KeyGeneration.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/KeyGeneration.java | package com.mmnaseri.utils.spring.data.dsl.mock;
import com.mmnaseri.utils.spring.data.domain.KeyGenerator;
/**
* Lets us set up how we want our keys to be generated
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/14/15)
*/
public interface KeyGeneration extends Implementation {
/**
* Sets the key generator to the provided instance
*
* @param keyGenerator the key generator
* @param <S> the type of the keys
* @return the rest of the configuration
*/
<S> Implementation generateKeysUsing(KeyGenerator<S> keyGenerator);
/**
* Sets the key generator to an instance of the provided type.
*
* @param generatorType the type of the key generator to use
* @param <S> the type of the keys the generator will be generating
* @param <G> the type of the generator
* @return the rest of the configuration
*/
<S, G extends KeyGenerator<S>> Implementation generateKeysUsing(Class<G> generatorType);
/**
* Tells the builder that we are not going to have any auto-generated keys
*
* @return the rest of the configuration
*/
Implementation withoutGeneratingKeys();
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/Implementation.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/Implementation.java | package com.mmnaseri.utils.spring.data.dsl.mock;
/**
* Lets us specify which implementations the repository should use
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/14/15)
*/
public interface Implementation extends End {
/**
* Tells the builder to use the given implementation
*
* @param implementation the implementation
* @return the rest of the configuration
*/
ImplementationAnd usingImplementation(Class<?> implementation);
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/Factory.java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/Factory.java | package com.mmnaseri.utils.spring.data.dsl.mock;
import com.mmnaseri.utils.spring.data.proxy.RepositoryFactory;
/**
* Specifies the factory for the repository mock builder
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/14/15)
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public interface Factory {
/**
* Tells the builder to use the specified factory
*
* @param factory the factory
* @return the rest of the configuration
*/
KeyGeneration useFactory(RepositoryFactory factory);
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.