DATACOUCH-3 - Renamed base package to org.springframework.data.couchbase.
This commit is contained in:
118
src/main/java/org/springframework/data/couchbase/cache/CouchbaseCache.java
vendored
Normal file
118
src/main/java/org/springframework/data/couchbase/cache/CouchbaseCache.java
vendored
Normal file
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* Copyright (C) 2009-2012 Couchbase, Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING
|
||||
* IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
package org.springframework.data.couchbase.cache;
|
||||
|
||||
import com.couchbase.client.CouchbaseClient;
|
||||
import net.spy.memcached.internal.OperationFuture;
|
||||
import org.springframework.cache.Cache;
|
||||
import org.springframework.cache.support.SimpleValueWrapper;
|
||||
|
||||
/**
|
||||
* The CouchbaseCache class implements the Spring Cache interface
|
||||
* on top of Couchbase Server and the Couchbase Java SDK.
|
||||
*/
|
||||
public class CouchbaseCache implements Cache {
|
||||
|
||||
/**
|
||||
* The actual CouchbaseClient instance.
|
||||
*/
|
||||
private final CouchbaseClient client;
|
||||
|
||||
/**
|
||||
* The name of the cache.
|
||||
*/
|
||||
private final String name;
|
||||
|
||||
/**
|
||||
* Construct the cache and pass in the CouchbaseClient instance.
|
||||
*
|
||||
* @param name the name of the cache reference.
|
||||
* @param client the CouchbaseClient instance.
|
||||
*/
|
||||
public CouchbaseCache(final String name, final CouchbaseClient client) {
|
||||
this.name = name;
|
||||
this.client = client;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the name of the cache.
|
||||
*
|
||||
* @return the name of the cache.
|
||||
*/
|
||||
public final String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the actual CouchbaseClient instance.
|
||||
*
|
||||
* @return the actual CouchbaseClient instance.
|
||||
*/
|
||||
public final CouchbaseClient getNativeCache() {
|
||||
return this.client;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an element from the cache.
|
||||
*
|
||||
* @param key the key to lookup against.
|
||||
* @return the fetched value from Couchbase.
|
||||
*/
|
||||
public final ValueWrapper get(final Object key) {
|
||||
String documentId = key.toString();
|
||||
Object result = this.client.get(documentId);
|
||||
return (result != null ? new SimpleValueWrapper(result) : null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Store a object in Couchbase.
|
||||
*
|
||||
* @param key the Key of the storable object.
|
||||
* @param value the Object to store.
|
||||
*/
|
||||
public final void put(final Object key, final Object value) {
|
||||
String documentId = key.toString();
|
||||
this.client.set(documentId, 0, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove an object from Couchbase.
|
||||
*
|
||||
* @param key the Key of the object to delete.
|
||||
*/
|
||||
public final void evict(final Object key) {
|
||||
String documentId = key.toString();
|
||||
this.client.delete(documentId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the complete cache.
|
||||
*
|
||||
* Note that this action is very destructive, so only use it with care.
|
||||
* Also note that "flush" may not be enabled on the bucket.
|
||||
*/
|
||||
public final void clear() {
|
||||
this.client.flush();
|
||||
}
|
||||
|
||||
}
|
||||
81
src/main/java/org/springframework/data/couchbase/cache/CouchbaseCacheManager.java
vendored
Normal file
81
src/main/java/org/springframework/data/couchbase/cache/CouchbaseCacheManager.java
vendored
Normal file
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* Copyright (C) 2009-2012 Couchbase, Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING
|
||||
* IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
package org.springframework.data.couchbase.cache;
|
||||
|
||||
import com.couchbase.client.CouchbaseClient;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Map;
|
||||
import org.springframework.cache.Cache;
|
||||
import org.springframework.cache.support.AbstractCacheManager;
|
||||
|
||||
/**
|
||||
* The CouchbaseCacheManager orchestrates CouchbaseCache instances.
|
||||
*
|
||||
* Since more than one current CouchbaseClient connection can be used
|
||||
* for caching, the CouchbaseCacheManager orchestrates and handles
|
||||
* them for the Spring Cache abstraction layer.
|
||||
*/
|
||||
public class CouchbaseCacheManager extends AbstractCacheManager {
|
||||
|
||||
/**
|
||||
* Holds the reference to all stored CouchbaseClient cache connections.
|
||||
*/
|
||||
private final HashMap<String, CouchbaseClient> clients;
|
||||
|
||||
/**
|
||||
* Construct a new CouchbaseCacheManager.
|
||||
*
|
||||
* @param clients one ore more CouchbaseClients to reference.
|
||||
*/
|
||||
public CouchbaseCacheManager(final HashMap<String, CouchbaseClient> clients) {
|
||||
this.clients = clients;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a Map of all CouchbaseClients with name.
|
||||
*
|
||||
* @return the actual CouchbaseClient instances.
|
||||
*/
|
||||
public final HashMap<String, CouchbaseClient> getClients() {
|
||||
return this.clients;
|
||||
}
|
||||
|
||||
/**
|
||||
* Populates all caches.
|
||||
*
|
||||
* @return a collection of loaded caches.
|
||||
*/
|
||||
@Override
|
||||
protected final Collection<? extends Cache> loadCaches() {
|
||||
Collection<Cache> caches = new LinkedHashSet<Cache>();
|
||||
|
||||
for (Map.Entry<String, CouchbaseClient> cache : this.clients.entrySet()) {
|
||||
caches.add(new CouchbaseCache(cache.getKey(), cache.getValue()));
|
||||
}
|
||||
|
||||
return caches;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* Copyright (C) 2009-2012 Couchbase, Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING
|
||||
* IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
package org.springframework.data.couchbase.config;
|
||||
|
||||
import com.couchbase.client.CouchbaseClient;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.type.filter.AnnotationTypeFilter;
|
||||
import org.springframework.data.annotation.Persistent;
|
||||
import org.springframework.data.couchbase.core.CouchbaseMappingContext;
|
||||
import org.springframework.data.couchbase.core.CouchbaseTemplate;
|
||||
import org.springframework.data.couchbase.core.convert.MappingCouchbaseConverter;
|
||||
import org.springframework.data.couchbase.core.mapping.Document;
|
||||
import org.springframework.util.ClassUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
/**
|
||||
* Base class for Spring Data Couchbase configuration using JavaConfig.
|
||||
*/
|
||||
@Configuration
|
||||
public abstract class AbstractCouchbaseConfiguration {
|
||||
|
||||
/**
|
||||
* Return the {@link CouchbaseClient} instance to connect to.
|
||||
*/
|
||||
@Bean
|
||||
public abstract CouchbaseClient couchbaseClient() throws Exception;
|
||||
|
||||
/**
|
||||
* Creates a {@link CouchbaseTemplate}.
|
||||
*/
|
||||
@Bean
|
||||
public CouchbaseTemplate couchbaseTemplate() throws Exception {
|
||||
return new CouchbaseTemplate(couchbaseClient(), mappingCouchbaseConverter());
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a {@link MappingCouchbaseConverter} using the configured {@link
|
||||
* #couchbaseMappingContext}.
|
||||
*/
|
||||
@Bean
|
||||
public MappingCouchbaseConverter mappingCouchbaseConverter() throws Exception {
|
||||
return new MappingCouchbaseConverter(couchbaseMappingContext());
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a {@link CouchbaseMappingContext} equipped with entity classes
|
||||
* scanned from the mapping base package.
|
||||
*/
|
||||
@Bean
|
||||
public CouchbaseMappingContext couchbaseMappingContext() throws Exception {
|
||||
CouchbaseMappingContext mappingContext = new CouchbaseMappingContext();
|
||||
mappingContext.setInitialEntitySet(getInitialEntitySet());
|
||||
return mappingContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* Scans the mapping base package for classes annotated with {@link Document}.
|
||||
*/
|
||||
protected Set<Class<?>> getInitialEntitySet() throws ClassNotFoundException {
|
||||
String basePackage = getMappingBasePackage();
|
||||
Set<Class<?>> initialEntitySet = new HashSet<Class<?>>();
|
||||
|
||||
if(StringUtils.hasText(basePackage)) {
|
||||
ClassPathScanningCandidateComponentProvider componentProvider =
|
||||
new ClassPathScanningCandidateComponentProvider(false);
|
||||
componentProvider.addIncludeFilter(
|
||||
new AnnotationTypeFilter(Document.class));
|
||||
componentProvider.addIncludeFilter(
|
||||
new AnnotationTypeFilter(Persistent.class));
|
||||
|
||||
for (BeanDefinition candidate :
|
||||
componentProvider.findCandidateComponents(basePackage)) {
|
||||
initialEntitySet.add(ClassUtils.forName(candidate.getBeanClassName(),
|
||||
AbstractCouchbaseConfiguration.class.getClassLoader()));
|
||||
}
|
||||
}
|
||||
|
||||
return initialEntitySet;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the base package to scan for mapped {@link Document}s. Will return
|
||||
* the package name of the configuration class (the concrete class, not this
|
||||
* one here) by default. So if you have a {@code com.acme.AppConfig} extending
|
||||
* {@link AbstractCouchbaseConfiguration} the base package will be considered
|
||||
* {@code com.acme} unless the method is overridden to implement alternate
|
||||
* behavior.
|
||||
*
|
||||
* @return the base package to scan for mapped {@link Document} classes or
|
||||
* {@literal null} to not enable scanning for entities.
|
||||
*/
|
||||
protected String getMappingBasePackage() {
|
||||
return getClass().getPackage().getName();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package org.springframework.data.couchbase.core;
|
||||
|
||||
|
||||
public interface BucketCallback<T> {
|
||||
T doInBucket();
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* Copyright (C) 2009-2012 Couchbase, Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING
|
||||
* IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
package org.springframework.data.couchbase.core;
|
||||
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.dao.DataAccessResourceFailureException;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.dao.support.PersistenceExceptionTranslator;
|
||||
|
||||
import com.couchbase.client.ObservedException;
|
||||
import com.couchbase.client.ObservedModifiedException;
|
||||
import com.couchbase.client.ObservedTimeoutException;
|
||||
import com.couchbase.client.vbucket.ConnectionException;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Simple {@link PersistenceExceptionTranslator} for Couchbase.
|
||||
*
|
||||
* Convert the given runtime exception to an appropriate exception from the
|
||||
* {@code org.springframework.dao} hierarchy. Return {@literal null} if no translation
|
||||
* is appropriate: any other exception may have resulted from user code, and should not
|
||||
* be translated.
|
||||
*/
|
||||
public class CouchbaseExceptionTranslator implements PersistenceExceptionTranslator {
|
||||
|
||||
/**
|
||||
* Translate Couchbase specific exceptions to spring exceptions if possible.
|
||||
*
|
||||
* @param ex the exception to translate.
|
||||
* @return the translated exception or null.
|
||||
*/
|
||||
@Override
|
||||
public final DataAccessException translateExceptionIfPossible(RuntimeException ex) {
|
||||
if (ex instanceof ConnectionException) {
|
||||
return new DataAccessResourceFailureException(ex.getMessage(), ex);
|
||||
}
|
||||
|
||||
if (ex instanceof ObservedException
|
||||
|| ex instanceof ObservedTimeoutException
|
||||
|| ex instanceof ObservedModifiedException) {
|
||||
return new DataIntegrityViolationException(ex.getMessage(), ex);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* Copyright (C) 2009-2012 Couchbase, Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING
|
||||
* IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
package org.springframework.data.couchbase.core;
|
||||
|
||||
import java.beans.PropertyDescriptor;
|
||||
import java.lang.reflect.Field;
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.data.couchbase.core.mapping.BasicCouchbasePersistentEntity;
|
||||
import org.springframework.data.couchbase.core.mapping.BasicCouchbasePersistentProperty;
|
||||
import org.springframework.data.couchbase.core.mapping.CouchbasePersistentProperty;
|
||||
import org.springframework.data.mapping.context.AbstractMappingContext;
|
||||
import org.springframework.data.mapping.model.SimpleTypeHolder;
|
||||
import org.springframework.data.util.TypeInformation;
|
||||
|
||||
public class CouchbaseMappingContext
|
||||
extends AbstractMappingContext<BasicCouchbasePersistentEntity<?>, CouchbasePersistentProperty>
|
||||
implements ApplicationContextAware {
|
||||
|
||||
private ApplicationContext context;
|
||||
|
||||
@Override
|
||||
protected <T> BasicCouchbasePersistentEntity<?> createPersistentEntity(TypeInformation<T> typeInformation) {
|
||||
BasicCouchbasePersistentEntity<T> entity = new BasicCouchbasePersistentEntity<T>(typeInformation);
|
||||
if(context != null) {
|
||||
entity.setApplicationContext(context);
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected CouchbasePersistentProperty createPersistentProperty(Field field, PropertyDescriptor descriptor, BasicCouchbasePersistentEntity<?> owner, SimpleTypeHolder simpleTypeHolder) {
|
||||
return new BasicCouchbasePersistentProperty(field, descriptor, owner, simpleTypeHolder);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext applicationContext)
|
||||
throws BeansException {
|
||||
this.context = applicationContext;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
/**
|
||||
* Copyright (C) 2009-2012 Couchbase, Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING
|
||||
* IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
package org.springframework.data.couchbase.core;
|
||||
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import org.springframework.data.couchbase.core.convert.CouchbaseConverter;
|
||||
|
||||
public interface CouchbaseOperations {
|
||||
|
||||
/**
|
||||
* Save the given object.
|
||||
*
|
||||
* When the document already exists (specified by its unique id),
|
||||
* then it will be overriden. Otherwise it will be created.
|
||||
*
|
||||
* <p>
|
||||
* The object is converted to a JSON representation using an instance of
|
||||
* {@link CouchbaseConverter}.
|
||||
* </p>
|
||||
*
|
||||
* @param objectToSave the object to store in the bucket.
|
||||
*/
|
||||
void save(Object objectToSave);
|
||||
|
||||
/**
|
||||
* Save a list of objects.
|
||||
*
|
||||
* When one of the documents already exists (specified by its unique id),
|
||||
* then it will be overriden. Otherwise it will be created.
|
||||
*
|
||||
* @param batchToSave the list of objects to store in the bucket.
|
||||
*/
|
||||
void save(Collection<? extends Object> batchToSave);
|
||||
|
||||
/**
|
||||
* Insert the given object.
|
||||
*
|
||||
* When the document already exists (specified by its unique id),
|
||||
* then it will not be overriden. Use the {@link CouchbaseOperations#save}
|
||||
* method for this.
|
||||
*
|
||||
* <p>
|
||||
* The object is converted to a JSON representation using an instance of
|
||||
* {@link CouchbaseConverter}.
|
||||
* </p>
|
||||
*
|
||||
* @param objectToSave the object to add to the bucket.
|
||||
*/
|
||||
void insert(Object objectToSave);
|
||||
|
||||
/**
|
||||
* Insert a list of objects.
|
||||
*
|
||||
* When one of the documents already exists (specified by its unique id),
|
||||
* then it will not be overriden. Use the {@link CouchbaseOperations#save}
|
||||
* method for this.
|
||||
*
|
||||
* @param batchToSave the list of objects to add to the bucket.
|
||||
*/
|
||||
void insert(Collection<? extends Object> batchToSave);
|
||||
|
||||
/**
|
||||
* Update the given object.
|
||||
*
|
||||
* When the document does not exists (specified by its unique id),
|
||||
* then it will not be created. Use the {@link CouchbaseOperations#save}
|
||||
* method for this.
|
||||
*
|
||||
* <p>
|
||||
* The object is converted to a JSON representation using an instance of
|
||||
* {@link CouchbaseConverter}.
|
||||
* </p>
|
||||
*
|
||||
* @param objectToSave the object to add to the bucket.
|
||||
*/
|
||||
void update(Object objectToSave);
|
||||
|
||||
/**
|
||||
* Insert a list of objects.
|
||||
*
|
||||
* When one of the documents does not exists (specified by its unique id),
|
||||
* then it will not be created. Use the {@link CouchbaseOperations#save}
|
||||
* method for this.
|
||||
*
|
||||
* @param batchToSave the list of objects to add to the bucket.
|
||||
*/
|
||||
void update(Collection<? extends Object> batchToSave);
|
||||
|
||||
/**
|
||||
* Find an object by its given Id and map it to the corresponding entity.
|
||||
*
|
||||
* @param id the unique ID of the document.
|
||||
* @param entityClass the entity to map to.
|
||||
* @return returns the found object or null otherwise.
|
||||
*/
|
||||
<T> T findById(String id, Class<T> entityClass);
|
||||
|
||||
/**
|
||||
* Checks if the given document exists.
|
||||
*
|
||||
* @param id the unique ID of the document.
|
||||
* @return whether the document could be found or not.
|
||||
*/
|
||||
boolean exists(String id);
|
||||
|
||||
/**
|
||||
* Remove the given object from the bucket by id.
|
||||
*
|
||||
* If the object is a String, it will be treated as the document key
|
||||
* directly.
|
||||
*
|
||||
* @param object the Object to remove.
|
||||
*/
|
||||
void remove(Object object);
|
||||
|
||||
/**
|
||||
* Remove a list of objects from the bucket by id.
|
||||
*
|
||||
* @param batchToRemove the list of Objects to remove.
|
||||
*/
|
||||
void remove(Collection<? extends Object> batchToRemove);
|
||||
|
||||
/**
|
||||
* Executes a BucketCallback translating any exceptions as necessary.
|
||||
*
|
||||
* Allows for returning a result object, that is a domain object or a
|
||||
* collection of domain objects.
|
||||
*
|
||||
* @param action the action to execute in the callback.
|
||||
* @param <T> the return type.
|
||||
* @return
|
||||
*/
|
||||
<T> T execute(BucketCallback<T> action);
|
||||
|
||||
/**
|
||||
* Returns the underlying {@link CouchbaseConverter}
|
||||
* @return
|
||||
*/
|
||||
CouchbaseConverter getConverter();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
/**
|
||||
* Copyright (C) 2009-2012 Couchbase, Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING
|
||||
* IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
package org.springframework.data.couchbase.core;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import net.spy.memcached.internal.OperationFuture;
|
||||
|
||||
import org.springframework.data.couchbase.core.convert.CouchbaseConverter;
|
||||
import org.springframework.data.couchbase.core.convert.MappingCouchbaseConverter;
|
||||
import org.springframework.data.couchbase.core.mapping.ConvertedCouchbaseDocument;
|
||||
import org.springframework.data.couchbase.core.mapping.CouchbasePersistentEntity;
|
||||
import org.springframework.data.couchbase.core.mapping.CouchbasePersistentProperty;
|
||||
import org.springframework.data.mapping.context.MappingContext;
|
||||
|
||||
import com.couchbase.client.CouchbaseClient;
|
||||
|
||||
public class CouchbaseTemplate implements CouchbaseOperations {
|
||||
|
||||
private CouchbaseClient client;
|
||||
private CouchbaseConverter couchbaseConverter;
|
||||
protected final MappingContext<? extends CouchbasePersistentEntity<?>,
|
||||
CouchbasePersistentProperty> mappingContext;
|
||||
private static final Collection<String> ITERABLE_CLASSES;
|
||||
private final CouchbaseExceptionTranslator exceptionTranslator =
|
||||
new CouchbaseExceptionTranslator();
|
||||
|
||||
static {
|
||||
Set<String> iterableClasses = new HashSet<String>();
|
||||
iterableClasses.add(List.class.getName());
|
||||
iterableClasses.add(Collection.class.getName());
|
||||
iterableClasses.add(Iterator.class.getName());
|
||||
ITERABLE_CLASSES = Collections.unmodifiableCollection(iterableClasses);
|
||||
}
|
||||
|
||||
public CouchbaseTemplate(final CouchbaseClient client) {
|
||||
this(client, null);
|
||||
}
|
||||
|
||||
public CouchbaseTemplate(final CouchbaseClient client,
|
||||
final CouchbaseConverter converter) {
|
||||
this.client = client;
|
||||
this.couchbaseConverter = converter == null ? getDefaultConverter(client) : converter;
|
||||
this.mappingContext = this.couchbaseConverter.getMappingContext();
|
||||
}
|
||||
|
||||
private CouchbaseConverter getDefaultConverter(final CouchbaseClient client) {
|
||||
MappingCouchbaseConverter converter = new MappingCouchbaseConverter(
|
||||
new CouchbaseMappingContext());
|
||||
converter.afterPropertiesSet();
|
||||
return converter;
|
||||
}
|
||||
|
||||
public final void insert(final Object objectToSave) {
|
||||
ensureNotIterable(objectToSave);
|
||||
|
||||
final ConvertedCouchbaseDocument converted =
|
||||
new ConvertedCouchbaseDocument();
|
||||
couchbaseConverter.write(objectToSave, converted);
|
||||
execute(new BucketCallback<OperationFuture<Boolean>>() {
|
||||
@Override
|
||||
public OperationFuture<Boolean> doInBucket() {
|
||||
return client.add(
|
||||
converted.getId(), converted.getExpiry(), converted.getRawValue());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public final void insert(final Collection<? extends Object> batchToSave) {
|
||||
Iterator<? extends Object> iter = batchToSave.iterator();
|
||||
while(iter.hasNext()) {
|
||||
insert(iter.next());
|
||||
}
|
||||
}
|
||||
|
||||
public void save(final Object objectToSave) {
|
||||
ensureNotIterable(objectToSave);
|
||||
|
||||
final ConvertedCouchbaseDocument converted =
|
||||
new ConvertedCouchbaseDocument();
|
||||
couchbaseConverter.write(objectToSave, converted);
|
||||
|
||||
execute(new BucketCallback<OperationFuture<Boolean>>() {
|
||||
@Override
|
||||
public OperationFuture<Boolean> doInBucket() {
|
||||
return client.set(
|
||||
converted.getId(), converted.getExpiry(), converted.getRawValue());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void save(final Collection<? extends Object> batchToSave) {
|
||||
Iterator<? extends Object> iter = batchToSave.iterator();
|
||||
while (iter.hasNext()) {
|
||||
save(iter.next());
|
||||
}
|
||||
}
|
||||
|
||||
public void update(final Object objectToSave) {
|
||||
ensureNotIterable(objectToSave);
|
||||
|
||||
final ConvertedCouchbaseDocument converted =
|
||||
new ConvertedCouchbaseDocument();
|
||||
couchbaseConverter.write(objectToSave, converted);
|
||||
|
||||
execute(new BucketCallback<OperationFuture<Boolean>>() {
|
||||
@Override
|
||||
public OperationFuture<Boolean> doInBucket() {
|
||||
return client.replace(
|
||||
converted.getId(), converted.getExpiry(), converted.getRawValue());
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
public void update(final Collection<? extends Object> batchToSave) {
|
||||
Iterator<? extends Object> iter = batchToSave.iterator();
|
||||
while (iter.hasNext()) {
|
||||
save(iter.next());
|
||||
}
|
||||
}
|
||||
|
||||
public final <T> T findById(final String id, final Class<T> entityClass) {
|
||||
String result = execute(new BucketCallback<String>() {
|
||||
@Override
|
||||
public String doInBucket() {
|
||||
return (String) client.get(id);
|
||||
}
|
||||
});
|
||||
|
||||
if (result == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
ConvertedCouchbaseDocument converted = new ConvertedCouchbaseDocument(id, result);
|
||||
return couchbaseConverter.read(entityClass, converted);
|
||||
}
|
||||
|
||||
public void remove(final Object objectToRemove) {
|
||||
ensureNotIterable(objectToRemove);
|
||||
|
||||
if (objectToRemove instanceof String) {
|
||||
execute(new BucketCallback<OperationFuture<Boolean>>() {
|
||||
@Override
|
||||
public OperationFuture<Boolean> doInBucket() {
|
||||
return client.delete((String) objectToRemove);
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
final ConvertedCouchbaseDocument converted = new ConvertedCouchbaseDocument();
|
||||
couchbaseConverter.write(objectToRemove, converted);
|
||||
|
||||
execute(new BucketCallback<OperationFuture<Boolean>>() {
|
||||
@Override
|
||||
public OperationFuture<Boolean> doInBucket() {
|
||||
return client.delete(converted.getId());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void remove(final Collection<? extends Object> batchToRemove) {
|
||||
Iterator<? extends Object> iter = batchToRemove.iterator();
|
||||
while (iter.hasNext()) {
|
||||
remove(iter.next());
|
||||
}
|
||||
}
|
||||
|
||||
public <T> T execute(final BucketCallback<T> action) {
|
||||
try {
|
||||
return action.doInBucket();
|
||||
} catch (RuntimeException e) {
|
||||
throw potentiallyConvertRuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean exists(final String id) {
|
||||
String result = execute(new BucketCallback<String>() {
|
||||
@Override
|
||||
public String doInBucket() {
|
||||
return (String) client.get(id);
|
||||
}
|
||||
});
|
||||
return result == null ? false : true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make sure the given object is not a iterable.
|
||||
*
|
||||
* @param o the object to verify.
|
||||
*/
|
||||
protected final void ensureNotIterable(Object o) {
|
||||
if (null != o) {
|
||||
if (o.getClass().isArray() || ITERABLE_CLASSES.contains(o.getClass().getName())) {
|
||||
throw new IllegalArgumentException("Cannot use a collection here.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private RuntimeException potentiallyConvertRuntimeException(final RuntimeException ex) {
|
||||
RuntimeException resolved = this.exceptionTranslator.translateExceptionIfPossible(ex);
|
||||
return resolved == null ? ex : resolved;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CouchbaseConverter getConverter() {
|
||||
return couchbaseConverter;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* Copyright (C) 2009-2012 Couchbase, Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING
|
||||
* IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
package org.springframework.data.couchbase.core.convert;
|
||||
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
import org.springframework.core.convert.ConversionService;
|
||||
import org.springframework.core.convert.support.GenericConversionService;
|
||||
import org.springframework.data.convert.EntityInstantiators;
|
||||
|
||||
public abstract class AbstractCouchbaseConverter implements CouchbaseConverter,
|
||||
InitializingBean {
|
||||
|
||||
protected final GenericConversionService conversionService;
|
||||
protected EntityInstantiators instantiators = new EntityInstantiators();
|
||||
|
||||
public AbstractCouchbaseConverter(
|
||||
GenericConversionService conversionService) {
|
||||
this.conversionService = conversionService;
|
||||
}
|
||||
|
||||
public ConversionService getConversionService() {
|
||||
return conversionService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterPropertiesSet() {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* Copyright (C) 2009-2012 Couchbase, Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING
|
||||
* IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
package org.springframework.data.couchbase.core.convert;
|
||||
|
||||
import org.springframework.data.convert.EntityConverter;
|
||||
import org.springframework.data.convert.EntityReader;
|
||||
import org.springframework.data.couchbase.core.mapping.ConvertedCouchbaseDocument;
|
||||
import org.springframework.data.couchbase.core.mapping.CouchbasePersistentEntity;
|
||||
import org.springframework.data.couchbase.core.mapping.CouchbasePersistentProperty;
|
||||
|
||||
public interface CouchbaseConverter extends
|
||||
EntityConverter<CouchbasePersistentEntity<?>,
|
||||
CouchbasePersistentProperty, Object, ConvertedCouchbaseDocument>,
|
||||
CouchbaseWriter<Object, ConvertedCouchbaseDocument>,
|
||||
EntityReader<Object, ConvertedCouchbaseDocument> {
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Copyright (C) 2009-2012 Couchbase, Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING
|
||||
* IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
package org.springframework.data.couchbase.core.convert;
|
||||
|
||||
import org.springframework.data.convert.EntityWriter;
|
||||
|
||||
public interface CouchbaseWriter<T, ConvertedCouchbaseDocument> extends
|
||||
EntityWriter<T, ConvertedCouchbaseDocument> {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
/**
|
||||
* Copyright (C) 2009-2012 Couchbase, Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING
|
||||
* IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
package org.springframework.data.couchbase.core.convert;
|
||||
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import org.codehaus.jackson.JsonEncoding;
|
||||
import org.codehaus.jackson.JsonFactory;
|
||||
import org.codehaus.jackson.JsonGenerator;
|
||||
import org.codehaus.jackson.map.ObjectMapper;
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.core.convert.support.ConversionServiceFactory;
|
||||
import org.springframework.data.convert.EntityInstantiator;
|
||||
import org.springframework.data.couchbase.core.mapping.ConvertedCouchbaseDocument;
|
||||
import org.springframework.data.couchbase.core.mapping.CouchbasePersistentEntity;
|
||||
import org.springframework.data.couchbase.core.mapping.CouchbasePersistentProperty;
|
||||
import org.springframework.data.mapping.context.MappingContext;
|
||||
import org.springframework.data.mapping.model.BeanWrapper;
|
||||
import org.springframework.data.mapping.model.MappingException;
|
||||
import org.springframework.data.mapping.model.ParameterValueProvider;
|
||||
import org.springframework.data.mapping.model.PersistentEntityParameterValueProvider;
|
||||
import org.springframework.data.mapping.model.PropertyValueProvider;
|
||||
import org.springframework.data.util.ClassTypeInformation;
|
||||
import org.springframework.data.util.TypeInformation;
|
||||
import org.springframework.data.mapping.PropertyHandler;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
public class MappingCouchbaseConverter extends AbstractCouchbaseConverter
|
||||
implements ApplicationContextAware {
|
||||
|
||||
protected ApplicationContext applicationContext;
|
||||
protected final MappingContext<? extends CouchbasePersistentEntity<?>,
|
||||
CouchbasePersistentProperty> mappingContext;
|
||||
protected boolean useFieldAccessOnly = true;
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public MappingCouchbaseConverter(MappingContext<? extends CouchbasePersistentEntity<?>,
|
||||
CouchbasePersistentProperty> mappingContext) {
|
||||
super(ConversionServiceFactory.createDefaultConversionService());
|
||||
|
||||
this.mappingContext = mappingContext;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MappingContext<? extends CouchbasePersistentEntity<?>,
|
||||
CouchbasePersistentProperty> getMappingContext() {
|
||||
return mappingContext;
|
||||
}
|
||||
|
||||
|
||||
private ParameterValueProvider<CouchbasePersistentProperty> getParameterProvider(
|
||||
CouchbasePersistentEntity<?> entity, ConvertedCouchbaseDocument source, Object parent) {
|
||||
|
||||
CouchbasePropertyValueProvider provider = new CouchbasePropertyValueProvider(source, parent);
|
||||
PersistentEntityParameterValueProvider<CouchbasePersistentProperty> parameterProvider =
|
||||
new PersistentEntityParameterValueProvider<CouchbasePersistentProperty>(
|
||||
entity, provider, parent);
|
||||
|
||||
return parameterProvider;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <R> R read(Class<R> type, ConvertedCouchbaseDocument doc) {
|
||||
return read(type, doc, null);
|
||||
}
|
||||
|
||||
public <R> R read(Class<R> type, final ConvertedCouchbaseDocument doc, Object parent) {
|
||||
final CouchbasePersistentEntity<R> entity = (CouchbasePersistentEntity<R>)
|
||||
mappingContext.getPersistentEntity(type);
|
||||
|
||||
ParameterValueProvider<CouchbasePersistentProperty> provider =
|
||||
getParameterProvider(entity, doc, parent);
|
||||
EntityInstantiator instantiator = instantiators.getInstantiatorFor(entity);
|
||||
R instance = instantiator.createInstance(entity, provider);
|
||||
|
||||
final BeanWrapper<CouchbasePersistentEntity<R>, R> wrapper =
|
||||
BeanWrapper.create(instance, conversionService);
|
||||
final R result = wrapper.getBean();
|
||||
|
||||
// Set properties not already set in the constructor
|
||||
entity.doWithProperties(new PropertyHandler<CouchbasePersistentProperty>() {
|
||||
public void doWithPersistentProperty(CouchbasePersistentProperty prop) {
|
||||
|
||||
boolean isConstructorProperty = entity.isConstructorArgument(prop);
|
||||
boolean hasValueForProperty = doc.containsField(prop.getFieldName());
|
||||
|
||||
if (!hasValueForProperty || isConstructorProperty) {
|
||||
return;
|
||||
}
|
||||
|
||||
Object obj = null;
|
||||
if(prop.isIdProperty()) {
|
||||
obj = doc.getId();
|
||||
} else {
|
||||
obj = doc.get(prop.getFieldName());
|
||||
}
|
||||
wrapper.setProperty(prop, obj, useFieldAccessOnly);
|
||||
}
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(Object source, ConvertedCouchbaseDocument target) {
|
||||
if(source == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
TypeInformation<? extends Object> type = ClassTypeInformation.from(source.getClass());
|
||||
try {
|
||||
writeInternal(source, target, type);
|
||||
} catch (IOException ex) {
|
||||
throw new MappingException("Could not translate to JSON while converting "
|
||||
+ source.getClass().getName());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
protected void writeInternal(final Object source,
|
||||
ConvertedCouchbaseDocument target, TypeInformation<?> type)
|
||||
throws IOException {
|
||||
CouchbasePersistentEntity<?> entity = mappingContext.getPersistentEntity(
|
||||
source.getClass());
|
||||
|
||||
if(entity == null) {
|
||||
throw new MappingException("No mapping metadata found for entity of type "
|
||||
+ source.getClass().getName());
|
||||
}
|
||||
|
||||
final CouchbasePersistentProperty idProperty = entity.getIdProperty();
|
||||
if(idProperty == null) {
|
||||
throw new MappingException("ID property required for entity of type "
|
||||
+ source.getClass().getName());
|
||||
}
|
||||
|
||||
final BeanWrapper<CouchbasePersistentEntity<Object>, Object> wrapper =
|
||||
BeanWrapper.create(source, conversionService);
|
||||
|
||||
String id = wrapper.getProperty(idProperty, String.class, false);
|
||||
target.setId(id);
|
||||
target.setExpiry(entity.getExpiry());
|
||||
|
||||
JsonFactory jsonFactory = new JsonFactory();
|
||||
OutputStream jsonStream = new ByteArrayOutputStream();
|
||||
final JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(
|
||||
jsonStream, JsonEncoding.UTF8);
|
||||
jsonGenerator.setCodec(new ObjectMapper());
|
||||
|
||||
jsonGenerator.writeStartObject();
|
||||
entity.doWithProperties(new PropertyHandler<CouchbasePersistentProperty>() {
|
||||
@Override
|
||||
public void doWithPersistentProperty(CouchbasePersistentProperty prop) {
|
||||
if(prop.equals(idProperty)) {
|
||||
return;
|
||||
}
|
||||
|
||||
Object propertyValue = wrapper.getProperty(prop, prop.getType(), false);
|
||||
if(propertyValue != null) {
|
||||
try {
|
||||
jsonGenerator.writeFieldName(prop.getFieldName());
|
||||
jsonGenerator.writeObject(propertyValue);
|
||||
} catch (IOException ex) {
|
||||
throw new MappingException("Could not translate to JSON while converting "
|
||||
+ source.getClass().getName());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
});
|
||||
jsonGenerator.writeEndObject();
|
||||
jsonGenerator.close();
|
||||
|
||||
target.setRawValue(jsonStream.toString());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext applicationContext)
|
||||
throws BeansException {
|
||||
this.applicationContext = applicationContext;
|
||||
}
|
||||
|
||||
private class CouchbasePropertyValueProvider implements PropertyValueProvider<CouchbasePersistentProperty> {
|
||||
|
||||
private final ConvertedCouchbaseDocument source;
|
||||
private final Object parent;
|
||||
|
||||
public CouchbasePropertyValueProvider(ConvertedCouchbaseDocument source, Object parent) {
|
||||
Assert.notNull(source);
|
||||
this.source = source;
|
||||
this.parent = parent;
|
||||
}
|
||||
|
||||
public <T> T getPropertyValue(CouchbasePersistentProperty property) {
|
||||
T value = null;
|
||||
|
||||
if(property.isIdProperty()) {
|
||||
value = (T) source.getId();
|
||||
} else {
|
||||
value = (T) source.get(property.getFieldName());
|
||||
}
|
||||
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* Copyright (C) 2009-2012 Couchbase, Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING
|
||||
* IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
package org.springframework.data.couchbase.core.mapping;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.context.expression.BeanFactoryAccessor;
|
||||
import org.springframework.context.expression.BeanFactoryResolver;
|
||||
import org.springframework.data.mapping.model.BasicPersistentEntity;
|
||||
import org.springframework.data.util.TypeInformation;
|
||||
import org.springframework.expression.spel.support.StandardEvaluationContext;
|
||||
|
||||
public class BasicCouchbasePersistentEntity<T>
|
||||
extends BasicPersistentEntity<T, CouchbasePersistentProperty>
|
||||
implements CouchbasePersistentEntity<T>, ApplicationContextAware {
|
||||
|
||||
private final StandardEvaluationContext context;
|
||||
|
||||
public BasicCouchbasePersistentEntity(TypeInformation<T> typeInformation) {
|
||||
super(typeInformation);
|
||||
|
||||
this.context = new StandardEvaluationContext();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext applicationContext)
|
||||
throws BeansException {
|
||||
context.addPropertyAccessor(new BeanFactoryAccessor());
|
||||
context.setBeanResolver(new BeanFactoryResolver(applicationContext));
|
||||
context.setRootObject(applicationContext);
|
||||
}
|
||||
|
||||
public int getExpiry() {
|
||||
org.springframework.data.couchbase.core.mapping.Document annotation =
|
||||
getType().getAnnotation(org.springframework.data.couchbase.core.mapping.Document.class);
|
||||
|
||||
if(annotation == null) {
|
||||
return 0;
|
||||
}
|
||||
return annotation.expiry();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* Copyright (C) 2009-2012 Couchbase, Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING
|
||||
* IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
package org.springframework.data.couchbase.core.mapping;
|
||||
|
||||
import java.beans.PropertyDescriptor;
|
||||
import java.lang.reflect.Field;
|
||||
import org.springframework.data.mapping.Association;
|
||||
import org.springframework.data.mapping.model.AnnotationBasedPersistentProperty;
|
||||
import org.springframework.data.mapping.model.SimpleTypeHolder;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
/**
|
||||
* Implements annotated property representations of a given Field instance.
|
||||
*
|
||||
* This object is used to gather information out of properties on objects
|
||||
* that need to be persisted. For example, it supports overriding of the
|
||||
* actual property name by providing custom annotations.
|
||||
*/
|
||||
public class BasicCouchbasePersistentProperty
|
||||
extends AnnotationBasedPersistentProperty<CouchbasePersistentProperty>
|
||||
implements CouchbasePersistentProperty {
|
||||
|
||||
/**
|
||||
* Create a new instance of the BasicCouchbasePersistentProperty class.
|
||||
*
|
||||
* @param field the field of the original reflection.
|
||||
* @param propertyDescriptor the PropertyDescriptor.
|
||||
* @param owner the original owner of the property.
|
||||
* @param simpleTypeHolder the type holder.
|
||||
*/
|
||||
public BasicCouchbasePersistentProperty(Field field,
|
||||
PropertyDescriptor propertyDescriptor, CouchbasePersistentEntity<?> owner,
|
||||
SimpleTypeHolder simpleTypeHolder) {
|
||||
super(field, propertyDescriptor, owner, simpleTypeHolder);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new Association.
|
||||
*/
|
||||
@Override
|
||||
protected Association<CouchbasePersistentProperty> createAssociation() {
|
||||
return new Association<CouchbasePersistentProperty>(this, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the field name of the property.
|
||||
*
|
||||
* The field name can be different from the actual property name by using a
|
||||
* custom annotation.
|
||||
*/
|
||||
@Override
|
||||
public String getFieldName() {
|
||||
org.springframework.data.couchbase.core.mapping.Field annotation = getField().
|
||||
getAnnotation(org.springframework.data.couchbase.core.mapping.Field.class);
|
||||
|
||||
return annotation != null && StringUtils.hasText(annotation.value())
|
||||
? annotation.value() : field.getName();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
/**
|
||||
* Copyright (C) 2009-2012 Couchbase, Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING
|
||||
* IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
package org.springframework.data.couchbase.core.mapping;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.codehaus.jackson.map.ObjectMapper;
|
||||
import org.codehaus.jackson.type.TypeReference;
|
||||
import org.springframework.data.mapping.model.MappingException;
|
||||
|
||||
public class ConvertedCouchbaseDocument {
|
||||
|
||||
private String id;
|
||||
|
||||
private String rawValue;
|
||||
|
||||
private int expiry;
|
||||
|
||||
private Map<String, Object> decoded;
|
||||
|
||||
public ConvertedCouchbaseDocument() {
|
||||
this("", "", 0);
|
||||
}
|
||||
|
||||
public ConvertedCouchbaseDocument(String id, String rawValue) {
|
||||
this(id, rawValue, 0);
|
||||
}
|
||||
|
||||
public ConvertedCouchbaseDocument(String id, String rawValue, int expiry) {
|
||||
this.id = id;
|
||||
this.rawValue = rawValue;
|
||||
this.expiry = expiry;
|
||||
this.decoded = new HashMap<String, Object>();
|
||||
parseJson();
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getRawValue() {
|
||||
return rawValue;
|
||||
}
|
||||
|
||||
public void setRawValue(String value) {
|
||||
this.rawValue = value;
|
||||
parseJson();
|
||||
|
||||
}
|
||||
|
||||
public int getExpiry() {
|
||||
return expiry;
|
||||
}
|
||||
|
||||
public void setExpiry(int expiry) {
|
||||
this.expiry = expiry;
|
||||
}
|
||||
|
||||
public boolean containsField(String fieldname) {
|
||||
return decoded.containsKey(fieldname);
|
||||
}
|
||||
|
||||
public Object get(String fieldname) {
|
||||
return decoded.get(fieldname);
|
||||
}
|
||||
|
||||
private void parseJson() {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
try {
|
||||
if(!getRawValue().isEmpty()) {
|
||||
Map<String, Object> converted = mapper.readValue(getRawValue(),
|
||||
new TypeReference<Map<String, Object>>() { });
|
||||
this.decoded = converted;
|
||||
}
|
||||
} catch(Exception e) {
|
||||
throw new MappingException("Error while decoding JSON object.", e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* Copyright (C) 2009-2012 Couchbase, Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING
|
||||
* IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
package org.springframework.data.couchbase.core.mapping;
|
||||
|
||||
import org.springframework.data.mapping.PersistentEntity;
|
||||
|
||||
public interface CouchbasePersistentEntity<T> extends
|
||||
PersistentEntity<T, CouchbasePersistentProperty> {
|
||||
|
||||
/**
|
||||
* Returns the expiry time for the document.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
int getExpiry();
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* Copyright (C) 2009-2012 Couchbase, Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING
|
||||
* IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
package org.springframework.data.couchbase.core.mapping;
|
||||
|
||||
import org.springframework.data.mapping.PersistentProperty;
|
||||
|
||||
|
||||
public interface CouchbasePersistentProperty extends
|
||||
PersistentProperty<CouchbasePersistentProperty> {
|
||||
|
||||
/**
|
||||
* Returns the field name of the property.
|
||||
*
|
||||
* The field name can be different from the actual property name by using a
|
||||
* custom annotation.
|
||||
*/
|
||||
String getFieldName();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* Copyright (C) 2009-2012 Couchbase, Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING
|
||||
* IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
package org.springframework.data.couchbase.core.mapping;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Inherited;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
import org.springframework.data.annotation.Persistent;
|
||||
|
||||
/**
|
||||
* Identifies a domain object to be persisted to Couchbase.
|
||||
*/
|
||||
@Persistent
|
||||
@Inherited
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({ ElementType.TYPE })
|
||||
public @interface Document {
|
||||
|
||||
/**
|
||||
* An optional expiry time for the document.
|
||||
*/
|
||||
int expiry() default 0;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
* To change this template, choose Tools | Templates
|
||||
* and open the template in the editor.
|
||||
*/
|
||||
package org.springframework.data.couchbase.core.mapping;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
|
||||
/**
|
||||
* Annotation to define custom metadata for document fields.
|
||||
*/
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface Field {
|
||||
|
||||
/**
|
||||
* The key to be used to store the field inside the document.
|
||||
*/
|
||||
String value() default "";
|
||||
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package org.springframework.data.couchbase.monitor;
|
||||
|
||||
import com.couchbase.client.CouchbaseClient;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.SocketAddress;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Base class to encapsulate common configuration settings.
|
||||
*/
|
||||
public abstract class AbstractMonitor {
|
||||
|
||||
private CouchbaseClient client;
|
||||
|
||||
private RestTemplate template = new RestTemplate();
|
||||
|
||||
protected AbstractMonitor(final CouchbaseClient client) {
|
||||
this.client = client;
|
||||
}
|
||||
|
||||
public CouchbaseClient getClient() {
|
||||
return client;
|
||||
}
|
||||
|
||||
protected RestTemplate getTemplate() {
|
||||
return template;
|
||||
}
|
||||
|
||||
protected String randomAvailableHostname() {
|
||||
List<SocketAddress> available = (ArrayList) client.getAvailableServers();
|
||||
Collections.shuffle(available);
|
||||
return ((InetSocketAddress) available.get(0)).getHostName();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches stats for all nodes.
|
||||
*
|
||||
* @return stats for each node
|
||||
*/
|
||||
protected Map<SocketAddress,Map<String,String>> getStats() {
|
||||
return client.getStats();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns stats for an individual node.
|
||||
*
|
||||
* @param node
|
||||
* @return
|
||||
*/
|
||||
protected Map<String, String> getStats(SocketAddress node) {
|
||||
return getStats().get(node);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* Copyright (C) 2009-2012 Couchbase, Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING
|
||||
* IN THE SOFTWARE.
|
||||
*/
|
||||
package org.springframework.data.couchbase.monitor;
|
||||
|
||||
import com.couchbase.client.CouchbaseClient;
|
||||
import org.springframework.jmx.export.annotation.ManagedAttribute;
|
||||
import org.springframework.jmx.export.annotation.ManagedResource;
|
||||
|
||||
import java.net.SocketAddress;
|
||||
|
||||
/**
|
||||
* Exposes basic client information.
|
||||
*/
|
||||
@ManagedResource(description = "Client Information")
|
||||
public class ClientInfo extends AbstractMonitor {
|
||||
|
||||
public ClientInfo(final CouchbaseClient client) {
|
||||
super(client);
|
||||
}
|
||||
|
||||
@ManagedAttribute(description = "Hostnames of connected nodes")
|
||||
public String getHostNames() {
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (SocketAddress node : getStats().keySet()) {
|
||||
result.append(node.toString()).append(",");
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
@ManagedAttribute(description = "Number of connected nodes")
|
||||
public int getNumberOfNodes() {
|
||||
return getStats().keySet().size();
|
||||
}
|
||||
|
||||
@ManagedAttribute(description = "Number of connected active nodes")
|
||||
public int getNumberOfActiveNodes() {
|
||||
return getClient().getAvailableServers().size();
|
||||
}
|
||||
|
||||
@ManagedAttribute(description = "Number of connected inactive nodes")
|
||||
public int getNumberOfInactiveNodes() {
|
||||
return getClient().getUnavailableServers().size();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package org.springframework.data.couchbase.monitor;
|
||||
|
||||
import com.couchbase.client.CouchbaseClient;
|
||||
import org.springframework.http.converter.HttpMessageConverter;
|
||||
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
|
||||
import org.springframework.jmx.export.annotation.ManagedAttribute;
|
||||
import org.springframework.jmx.export.annotation.ManagedMetric;
|
||||
import org.springframework.jmx.export.annotation.ManagedResource;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
|
||||
/**
|
||||
* Exposes basic cluster information.
|
||||
*/
|
||||
@ManagedResource(description = "Cluster Information")
|
||||
public class ClusterInfo extends AbstractMonitor {
|
||||
|
||||
public ClusterInfo(final CouchbaseClient client) {
|
||||
super(client);
|
||||
}
|
||||
|
||||
@ManagedMetric(description = "Total RAM assigned")
|
||||
public long getTotalRAMAssigned() {
|
||||
return (Long) parseStorageTotals().get("ram").get("total");
|
||||
}
|
||||
|
||||
@ManagedMetric(description = "Total RAM used")
|
||||
public long getTotalRAMUsed() {
|
||||
return (Long) parseStorageTotals().get("ram").get("used");
|
||||
}
|
||||
|
||||
@ManagedMetric(description = "Total Disk Space assigned")
|
||||
public long getTotalDiskAssigned() {
|
||||
return (Long) parseStorageTotals().get("hdd").get("total");
|
||||
}
|
||||
|
||||
@ManagedMetric(description = "Total Disk Space used")
|
||||
public long getTotalDiskUsed() {
|
||||
return (Long) parseStorageTotals().get("hdd").get("used");
|
||||
}
|
||||
|
||||
@ManagedMetric(description = "Total Disk Space free")
|
||||
public long getTotalDiskFree() {
|
||||
return (Long) parseStorageTotals().get("hdd").get("free");
|
||||
}
|
||||
|
||||
@ManagedAttribute(description = "Cluster is Balanced")
|
||||
public boolean getIsBalanced() {
|
||||
return (Boolean) fetchPoolInfo().get("balanced");
|
||||
}
|
||||
|
||||
@ManagedAttribute(description = "Rebalance Status")
|
||||
public String getRebalanceStatus() {
|
||||
return (String) fetchPoolInfo().get("rebalanceStatus");
|
||||
}
|
||||
|
||||
@ManagedAttribute(description = "Maximum Available Buckets")
|
||||
public int getMaxBuckets() {
|
||||
return (Integer) fetchPoolInfo().get("maxBucketCount");
|
||||
}
|
||||
|
||||
private HashMap<String, Object> fetchPoolInfo() {
|
||||
return getTemplate().getForObject("http://"
|
||||
+ randomAvailableHostname() + ":8091/pools/default", HashMap.class);
|
||||
}
|
||||
|
||||
private HashMap<String, HashMap> parseStorageTotals() {
|
||||
HashMap<String, Object> stats = fetchPoolInfo();
|
||||
return (HashMap<String, HashMap>) stats.get("storageTotals");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package org.springframework.data.couchbase.repository;
|
||||
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* Couchbase specific {@link org.springframework.data.repository.Repository}
|
||||
* interface.
|
||||
*/
|
||||
public interface CouchbaseRepository<T, ID extends Serializable> extends CrudRepository<T, ID> {
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package org.springframework.data.couchbase.repository.config;
|
||||
|
||||
import org.springframework.data.repository.config.RepositoryBeanDefinitionRegistrarSupport;
|
||||
import org.springframework.data.repository.config.RepositoryConfigurationExtension;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
|
||||
|
||||
public class CouchbaseRepositoriesRegistrar extends RepositoryBeanDefinitionRegistrarSupport {
|
||||
|
||||
@Override
|
||||
protected Class<? extends Annotation> getAnnotation() {
|
||||
return EnableCouchbaseRepositories.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected RepositoryConfigurationExtension getExtension() {
|
||||
return new CouchbaseRepositoryConfigurationExtension();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package org.springframework.data.couchbase.repository.config;
|
||||
|
||||
|
||||
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
|
||||
import org.springframework.core.annotation.AnnotationAttributes;
|
||||
import org.springframework.data.config.ParsingUtils;
|
||||
import org.springframework.data.couchbase.repository.support.CouchbaseRepositoryFactoryBean;
|
||||
import org.springframework.data.repository.config.AnnotationRepositoryConfigurationSource;
|
||||
import org.springframework.data.repository.config.RepositoryConfigurationExtensionSupport;
|
||||
import org.springframework.data.repository.config.XmlRepositoryConfigurationSource;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
public class CouchbaseRepositoryConfigurationExtension extends RepositoryConfigurationExtensionSupport {
|
||||
|
||||
private static final String COUCHBASE_TEMPLATE_REF = "couchbase-template-ref";
|
||||
|
||||
@Override
|
||||
protected String getModulePrefix() {
|
||||
return "couchbase";
|
||||
}
|
||||
|
||||
public String getRepositoryFactoryClassName() {
|
||||
return CouchbaseRepositoryFactoryBean.class.getName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postProcess(BeanDefinitionBuilder builder, XmlRepositoryConfigurationSource config) {
|
||||
Element element = config.getElement();
|
||||
ParsingUtils.setPropertyReference(builder, element, COUCHBASE_TEMPLATE_REF, "couchbaseOperations");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postProcess(BeanDefinitionBuilder builder, AnnotationRepositoryConfigurationSource config) {
|
||||
AnnotationAttributes attributes = config.getAttributes();
|
||||
builder.addPropertyReference("couchbaseOperations", attributes.getString("couchbaseTemplateRef"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package org.springframework.data.couchbase.repository.config;
|
||||
|
||||
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.context.annotation.ComponentScan.Filter;
|
||||
import org.springframework.data.couchbase.repository.support.CouchbaseRepositoryFactoryBean;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Inherited;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* Annotation to activate Couchbase repositories. If no base package is configured through either {@link #value()},
|
||||
* {@link #basePackages()} or {@link #basePackageClasses()} it will trigger scanning of the package of annotated class.
|
||||
*/
|
||||
@Target(ElementType.TYPE)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
@Inherited
|
||||
@Import(CouchbaseRepositoriesRegistrar.class)
|
||||
public @interface EnableCouchbaseRepositories {
|
||||
|
||||
/**
|
||||
* Alias for the {@link #basePackages()} attribute. Allows for more concise annotation declarations e.g.:
|
||||
* {@code @EnableCouchbaseRepositories("org.my.pkg")} instead of {@code @EnableCouchbaseRepositories(basePackages="org.my.pkg")}.
|
||||
*/
|
||||
String[] value() default {};
|
||||
|
||||
/**
|
||||
* Base packages to scan for annotated components. {@link #value()} is an alias for (and mutually exclusive with) this
|
||||
* attribute. Use {@link #basePackageClasses()} for a type-safe alternative to String-based package names.
|
||||
*/
|
||||
String[] basePackages() default {};
|
||||
|
||||
/**
|
||||
* Type-safe alternative to {@link #basePackages()} for specifying the packages to scan for annotated components. The
|
||||
* package of each class specified will be scanned. Consider creating a special no-op marker class or interface in
|
||||
* each package that serves no purpose other than being referenced by this attribute.
|
||||
*/
|
||||
Class<?>[] basePackageClasses() default {};
|
||||
|
||||
/**
|
||||
* Specifies which types are eligible for component scanning. Further narrows the set of candidate components from
|
||||
* everything in {@link #basePackages()} to everything in the base packages that matches the given filter or filters.
|
||||
*/
|
||||
Filter[] includeFilters() default {};
|
||||
|
||||
/**
|
||||
* Specifies which types are not eligible for component scanning.
|
||||
*/
|
||||
Filter[] excludeFilters() default {};
|
||||
|
||||
/**
|
||||
* Returns the postfix to be used when looking up custom repository implementations. Defaults to {@literal Impl}. So
|
||||
* for a repository named {@code PersonRepository} the corresponding implementation class will be looked up scanning
|
||||
* for {@code PersonRepositoryImpl}.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
String repositoryImplementationPostfix() default "";
|
||||
|
||||
/**
|
||||
* Configures the location of where to find the Spring Data named queries properties file. Will default to
|
||||
* {@code META-INFO/couchbase-named-queries.properties}.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
String namedQueriesLocation() default "";
|
||||
|
||||
|
||||
/**
|
||||
* Returns the {@link FactoryBean} class to be used for each repository instance. Defaults to
|
||||
* {@link CouchbaseRepositoryFactoryBean}.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
Class<?> repositoryFactoryBeanClass() default CouchbaseRepositoryFactoryBean.class;
|
||||
|
||||
/**
|
||||
* Configures the name of the {@link CouchbaseTemplate} bean to be used with the repositories detected.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
String couchbaseTemplateRef() default "couchbaseTemplate";
|
||||
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package org.springframework.data.couchbase.repository.query;
|
||||
|
||||
import org.springframework.data.repository.core.EntityInformation;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
|
||||
public interface CouchbaseEntityInformation<T, ID extends Serializable> extends EntityInformation<T, ID> {
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package org.springframework.data.couchbase.repository.support;
|
||||
|
||||
|
||||
import org.springframework.data.couchbase.core.CouchbaseOperations;
|
||||
import org.springframework.data.couchbase.core.mapping.CouchbasePersistentEntity;
|
||||
import org.springframework.data.couchbase.core.mapping.CouchbasePersistentProperty;
|
||||
import org.springframework.data.couchbase.repository.query.CouchbaseEntityInformation;
|
||||
import org.springframework.data.mapping.context.MappingContext;
|
||||
import org.springframework.data.mapping.model.MappingException;
|
||||
import org.springframework.data.repository.core.RepositoryMetadata;
|
||||
import org.springframework.data.repository.core.support.RepositoryFactorySupport;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* Factory to create {@link CouchbaseRepository} instances.
|
||||
*/
|
||||
public class CouchbaseRepositoryFactory extends RepositoryFactorySupport {
|
||||
|
||||
private final CouchbaseOperations couchbaseOperations;
|
||||
private final MappingContext<? extends CouchbasePersistentEntity<?>,
|
||||
CouchbasePersistentProperty> mappingContext;
|
||||
|
||||
public CouchbaseRepositoryFactory(final CouchbaseOperations couchbaseOperations) {
|
||||
Assert.notNull(couchbaseOperations);
|
||||
this.couchbaseOperations = couchbaseOperations;
|
||||
mappingContext = couchbaseOperations.getConverter().getMappingContext();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T, ID extends Serializable> CouchbaseEntityInformation<T, ID>
|
||||
getEntityInformation(Class<T> domainClass) {
|
||||
CouchbasePersistentEntity<?> entity = mappingContext.getPersistentEntity(domainClass);
|
||||
|
||||
if(entity == null) {
|
||||
throw new MappingException(String.format("Could not lookup mapping metadata for domain class %s!",
|
||||
domainClass.getName()));
|
||||
}
|
||||
return new MappingCouchbaseEntityInformation<T, ID>((CouchbasePersistentEntity<T>) entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object getTargetRepository(RepositoryMetadata metadata) {
|
||||
CouchbaseEntityInformation<?, Serializable> entityInformation =
|
||||
getEntityInformation(metadata.getDomainType());
|
||||
return new SimpleCouchbaseRepository(entityInformation, couchbaseOperations);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Class<?> getRepositoryBaseClass(RepositoryMetadata repositoryMetadata) {
|
||||
return SimpleCouchbaseRepository.class;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package org.springframework.data.couchbase.repository.support;
|
||||
|
||||
|
||||
import org.springframework.data.couchbase.core.CouchbaseOperations;
|
||||
import org.springframework.data.repository.Repository;
|
||||
import org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport;
|
||||
import org.springframework.data.repository.core.support.RepositoryFactorySupport;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class CouchbaseRepositoryFactoryBean<T extends Repository<S, ID>, S, ID extends Serializable> extends
|
||||
RepositoryFactoryBeanSupport<T, S, ID> {
|
||||
|
||||
private CouchbaseOperations operations;
|
||||
|
||||
public void setCouchbaseOperations(CouchbaseOperations operations) {
|
||||
this.operations = operations;
|
||||
setMappingContext(operations.getConverter().getMappingContext());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected RepositoryFactorySupport createRepositoryFactory() {
|
||||
return getFactoryInstance(operations);
|
||||
}
|
||||
|
||||
private RepositoryFactorySupport getFactoryInstance(CouchbaseOperations operations) {
|
||||
return new CouchbaseRepositoryFactory(operations);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterPropertiesSet() {
|
||||
super.afterPropertiesSet();
|
||||
Assert.notNull(operations, "CouchbaseTemplate must not be null!");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package org.springframework.data.couchbase.repository.support;
|
||||
|
||||
import org.springframework.data.couchbase.core.mapping.CouchbasePersistentEntity;
|
||||
import org.springframework.data.couchbase.core.mapping.CouchbasePersistentProperty;
|
||||
import org.springframework.data.couchbase.repository.query.CouchbaseEntityInformation;
|
||||
import org.springframework.data.mapping.model.BeanWrapper;
|
||||
import org.springframework.data.repository.core.support.AbstractEntityInformation;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
|
||||
public class MappingCouchbaseEntityInformation<T, ID extends Serializable>
|
||||
extends AbstractEntityInformation<T, ID>
|
||||
implements CouchbaseEntityInformation<T, ID> {
|
||||
|
||||
private final CouchbasePersistentEntity<T> entityMetadata;
|
||||
|
||||
public MappingCouchbaseEntityInformation(CouchbasePersistentEntity<T> entity) {
|
||||
super(entity.getType());
|
||||
entityMetadata = entity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ID getId(T entity) {
|
||||
CouchbasePersistentProperty idProperty = entityMetadata.getIdProperty();
|
||||
|
||||
if(idProperty == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return (ID) BeanWrapper.create(entity, null).getProperty(idProperty);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<ID> getIdType() {
|
||||
return (Class<ID>) entityMetadata.getIdProperty().getType();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package org.springframework.data.couchbase.repository.support;
|
||||
|
||||
import org.springframework.data.couchbase.core.CouchbaseOperations;
|
||||
import org.springframework.data.couchbase.repository.CouchbaseRepository;
|
||||
import org.springframework.data.couchbase.repository.query.CouchbaseEntityInformation;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Repository base implementation for Couchbase.
|
||||
*/
|
||||
public class SimpleCouchbaseRepository<T, ID extends Serializable> implements CouchbaseRepository<T, ID> {
|
||||
|
||||
private final CouchbaseOperations couchbaseOperations;
|
||||
private final CouchbaseEntityInformation<T, String> entityInformation;
|
||||
|
||||
|
||||
public SimpleCouchbaseRepository(CouchbaseEntityInformation<T, String> metadata, CouchbaseOperations couchbaseOperations) {
|
||||
Assert.notNull(couchbaseOperations);
|
||||
Assert.notNull(metadata);
|
||||
|
||||
entityInformation = metadata;
|
||||
this.couchbaseOperations = couchbaseOperations;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <S extends T> S save(S entity) {
|
||||
Assert.notNull(entity, "Entity must not be null!");
|
||||
|
||||
couchbaseOperations.save(entity);
|
||||
return entity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <S extends T> Iterable<S> save(Iterable<S> entities) {
|
||||
Assert.notNull(entities, "The given Iterable of entities must not be null!");
|
||||
|
||||
List<S> result = new ArrayList<S>();
|
||||
for(S entity : entities) {
|
||||
save(entity);
|
||||
result.add(entity);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T findOne(ID id) {
|
||||
Assert.notNull(id, "The given id must not be null!");
|
||||
return couchbaseOperations.findById(id.toString(), entityInformation.getJavaType());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean exists(ID id) {
|
||||
Assert.notNull(id, "The given id must not be null!");
|
||||
return couchbaseOperations.exists(id.toString());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(ID id) {
|
||||
Assert.notNull(id, "The given id must not be null!");
|
||||
couchbaseOperations.remove(id.toString());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(T entity) {
|
||||
Assert.notNull(entity, "The given id must not be null!");
|
||||
couchbaseOperations.remove(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(Iterable<? extends T> entities) {
|
||||
Assert.notNull(entities, "The given Iterable of entities must not be null!");
|
||||
for (T entity: entities) {
|
||||
couchbaseOperations.remove(entity);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterable<T> findAll() {
|
||||
throw new UnsupportedOperationException("findAll is not supported in the current version!");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterable<T> findAll(Iterable<ID> ids) {
|
||||
throw new UnsupportedOperationException("findAll is not supported in the current version!");
|
||||
}
|
||||
|
||||
@Override
|
||||
public long count() {
|
||||
throw new UnsupportedOperationException("count is not supported in the current version!");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteAll() {
|
||||
throw new UnsupportedOperationException("deleteAll is not supported in the current version!");
|
||||
}
|
||||
|
||||
protected CouchbaseOperations getCouchbaseOperations() {
|
||||
return couchbaseOperations;
|
||||
}
|
||||
|
||||
protected CouchbaseEntityInformation<T, String> getEntityInformation() {
|
||||
return entityInformation;
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user