Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2011-2014 the original author or authors.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 package org.springframework.data.mongodb.core.convert;
 
 import java.util.List;
 import java.util.Set;
 
 import  org.springframework.core.convert.ConversionException;
 import  org.springframework.core.convert.ConversionService;
 import  org.springframework.core.convert.converter.Converter;
 import  org.springframework.util.Assert;
 
A helper class to encapsulate any modifications of a Query object before it gets submitted to the database.

Author(s):
Jon Brisbin
Oliver Gierke
Patryk Wasik
Thomas Darimont
Christoph Strobl
 
 public class QueryMapper {
 
 	private static final List<StringDEFAULT_ID_NAMES = Arrays.asList("id""_id");
 
 	private final ConversionService conversionService;
 	private final MongoConverter converter;
Creates a new QueryMapper with the given MongoConverter.

Parameters:
converter must not be null.
 
 	public QueryMapper(MongoConverter converter) {
 
 		Assert.notNull(converter);
 
 		this. = converter.getConversionService();
 		this. = converter;
 		this. = converter.getMappingContext();
 	}

Replaces the property keys used in the given DBObject with the appropriate keys by using the PersistentEntity metadata.

Parameters:
query must not be null.
entity can be null.
Returns:
 
 	@SuppressWarnings("deprecation")
 	public DBObject getMappedObject(DBObject queryMongoPersistentEntity<?> entity) {
 
 		if (isNestedKeyword(query)) {
 			return getMappedKeyword(new Keyword(query), entity);
 		}
 
 		DBObject result = new BasicDBObject();
 
 		for (String key : query.keySet()) {
 
 			// TODO: remove one once QueryMapper can work with Query instances directly
 			if (Query.isRestrictedTypeKey(key)) {
				@SuppressWarnings("unchecked")
				Set<Class<?>> restrictedTypes = (Set<Class<?>>) query.get(key);
				this..getTypeMapper().writeTypeRestrictions(resultrestrictedTypes);
				continue;
			}
			if (isKeyword(key)) {
				result.putAll(getMappedKeyword(new Keyword(querykey), entity));
				continue;
			}
			Field field = createPropertyField(entitykey);
			Entry<StringObjectentry = getMappedObjectForField(fieldquery.get(key));
			result.put(entry.getKey(), entry.getValue());
		}
		return result;
	}

Extracts the mapped object value for given field out of rawValue taking nested Keywords into account

Parameters:
field
rawValue
Returns:
	protected Entry<StringObjectgetMappedObjectForField(Field fieldObject rawValue) {
		String key = field.getMappedKey();
		Object value;
		if (isNestedKeyword(rawValue) && !field.isIdField()) {
			Keyword keyword = new Keyword((DBObjectrawValue);
			value = getMappedKeyword(fieldkeyword);
else {
			value = getMappedValue(fieldrawValue);
		}
		return Collections.singletonMap(keyvalue).entrySet().iterator().next();
	}

Parameters:
entity
key
mappingContext
Returns:
			MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentPropertymappingContext) {
		return entity == null ? new Field(key) : new MetadataBackedField(keyentitymappingContext);
	}

Returns the given DBObject representing a keyword by mapping the keyword's value.

Parameters:
keyword the DBObject representing a keyword (e.g. $ne : … )
entity
Returns:
	protected DBObject getMappedKeyword(Keyword keywordMongoPersistentEntity<?> entity) {
		// $or/$nor
		if (keyword.isOrOrNor() || keyword.hasIterableValue()) {
			Iterable<?> conditions = keyword.getValue();
			BasicDBList newConditions = new BasicDBList();
			for (Object condition : conditions) {
				newConditions.add(condition instanceof DBObject ? getMappedObject((DBObjectconditionentity)
convertSimpleOrDBObject(conditionentity));
			}
			return new BasicDBObject(keyword.getKey(), newConditions);
		}
		return new BasicDBObject(keyword.getKey(), convertSimpleOrDBObject(keyword.getValue(), entity));
	}

Returns the mapped keyword considered defining a criteria for the given property.

Parameters:
property
keyword
Returns:
	protected DBObject getMappedKeyword(Field propertyKeyword keyword) {
		boolean needsAssociationConversion = property.isAssociation() && !keyword.isExists();
		Object value = keyword.getValue();
		Object convertedValue = needsAssociationConversion ? convertAssociation(valueproperty) : getMappedValue(
				property.with(keyword.getKey()), value);
		return new BasicDBObject(keyword.keyconvertedValue);
	}

Returns the mapped value for the given source object assuming it's a value for the given MongoPersistentProperty.

Parameters:
value the source object to be mapped
property the property the value is a value for
newKey the key the value will be bound to eventually
Returns:
	protected Object getMappedValue(Field documentFieldObject value) {
		if (documentField.isIdField()) {
			if (value instanceof DBObject) {
				DBObject valueDbo = (DBObjectvalue;
				DBObject resultDbo = new BasicDBObject(valueDbo.toMap());
				if (valueDbo.containsField("$in") || valueDbo.containsField("$nin")) {
					String inKey = valueDbo.containsField("$in") ? "$in" : "$nin";
					List<Objectids = new ArrayList<Object>();
					for (Object id : (Iterable<?>) valueDbo.get(inKey)) {
						ids.add(convertId(id));
					}
					resultDbo.put(inKeyids.toArray(new Object[ids.size()]));
else if (valueDbo.containsField("$ne")) {
					resultDbo.put("$ne"convertId(valueDbo.get("$ne")));
else {
					return getMappedObject(resultDbonull);
				}
				return resultDbo;
else {
				return convertId(value);
			}
		}
		if (isNestedKeyword(value)) {
			return getMappedKeyword(new Keyword((DBObjectvalue), null);
		}
		if (isAssociationConversionNecessary(documentFieldvalue)) {
			return convertAssociation(valuedocumentField);
		}
		return convertSimpleOrDBObject(valuedocumentField.getPropertyEntity());
	}

Returns whether the given Field represents an association reference that together with the given value requires conversion to a org.springframework.data.mongodb.core.mapping.DBRef object. We check whether the type of the given value is compatible with the type of the given document field in order to deal with potential query field exclusions, since MongoDB uses the int 0 as an indicator for an excluded field.

Parameters:
documentField
value
Returns:
	protected boolean isAssociationConversionNecessary(Field documentFieldObject value) {
		return documentField.isAssociation() && value != null
				&& (documentField.getProperty().getActualType().isAssignableFrom(value.getClass()) //
	}

Retriggers mapping if the given source is a DBObject or simply invokes the

Parameters:
source
entity
Returns:
		if (source instanceof BasicDBList) {
			return delegateConvertToMongoType(sourceentity);
		}
		if (source instanceof DBObject) {
			return getMappedObject((DBObjectsourceentity);
		}
		return delegateConvertToMongoType(sourceentity);
	}

Converts the given source Object to a mongo type with the type information of the original source type omitted. Subclasses may overwrite this method to retain the type information of the source type on the resulting mongo type.

Parameters:
source
entity
Returns:
the converted mongo type or null if source is null
	}
	protected Object convertAssociation(Object sourceField field) {
		return convertAssociation(sourcefield.getProperty());
	}

Converts the given source assuming it's actually an association to another object.

Parameters:
source
property
Returns:
	protected Object convertAssociation(Object sourceMongoPersistentProperty property) {
		if (property == null || source == null || source instanceof DBRef) {
			return source;
		}
		if (source instanceof Iterable) {
			BasicDBList result = new BasicDBList();
			for (Object element : (Iterable<?>) source) {
				result.add(createDbRefFor(elementproperty));
			}
			return result;
		}
		if (property.isMap()) {
			BasicDBObject result = new BasicDBObject();
			DBObject dbObject = (DBObjectsource;
			for (String key : dbObject.keySet()) {
				result.put(keycreateDbRefFor(dbObject.get(key), property));
			}
			return result;
		}
		return createDbRefFor(sourceproperty);
	}
	private DBRef createDbRefFor(Object sourceMongoPersistentProperty property) {
		if (source instanceof DBRef) {
			return (DBRefsource;
		}
		return .toDBRef(sourceproperty);
	}

Converts the given raw id value into either ObjectId or String.

Parameters:
id
Returns:
	public Object convertId(Object id) {
		try {
			return .convert(idObjectId.class);
catch (ConversionException e) {
			// Ignore
		}
		return delegateConvertToMongoType(idnull);
	}

Returns whether the given Object is a keyword, i.e. if it's a DBObject with a keyword key.

Parameters:
candidate
Returns:
	protected boolean isNestedKeyword(Object candidate) {
		if (!(candidate instanceof BasicDBObject)) {
			return false;
		}
		BasicDBObject dbObject = (BasicDBObjectcandidate;
		Set<Stringkeys = dbObject.keySet();
		if (keys.size() != 1) {
			return false;
		}
		return isKeyword(keys.iterator().next().toString());
	}

Returns whether the given String is a MongoDB keyword. The default implementation will check against the set of registered keywords returned by getKeywords().

Parameters:
candidate
Returns:
	protected boolean isKeyword(String candidate) {
		return candidate.startsWith("$");
	}

Value object to capture a query keyword representation.

Author(s):
Oliver Gierke
	static class Keyword {
		private static final String N_OR_PATTERN = "\\$.*or";
		private final String key;
		private final Object value;
		public Keyword(DBObject sourceString key) {
			this. = key;
			this. = source.get(key);
		}
		public Keyword(DBObject dbObject) {
			Set<Stringkeys = dbObject.keySet();
			Assert.isTrue(keys.size() == 1, "Can only use a single value DBObject!");
			this. = keys.iterator().next();
			this. = dbObject.get();
		}

Returns whether the current keyword is the $exists keyword.

Returns:
		public boolean isExists() {
			return "$exists".equalsIgnoreCase();
		}
		public boolean isOrOrNor() {
		}
		public boolean hasIterableValue() {
			return  instanceof Iterable;
		}
		public String getKey() {
			return ;
		}
		@SuppressWarnings("unchecked")
		public <T> T getValue() {
			return (T) ;
		}
	}

Value object to represent a field and its meta-information.

Author(s):
Oliver Gierke
	protected static class Field {
		private static final String ID_KEY = "_id";
		protected final String name;

Creates a new DocumentField without meta-information but the given name.

Parameters:
name must not be null or empty.
		public Field(String name) {
			Assert.hasText(name"Name must not be null!");
			this. = name;
		}

Returns a new DocumentField with the given name.

Parameters:
name must not be null or empty.
Returns:
		public Field with(String name) {
			return new Field(name);
		}

Returns whether the current field is the id field.

Returns:
		public boolean isIdField() {
			return .equals();
		}

Returns the underlying MongoPersistentProperty backing the field. For path traversals this will be the property that represents the value to handle. This means it'll be the leaf property for plain paths or the association property in case we refer to an association somewhere in the path.

Returns:
			return null;
		}

Returns the MongoPersistentEntity that field is conatined in.

Returns:
			return null;
		}

Returns whether the field represents an association.

Returns:
		public boolean isAssociation() {
			return false;
		}

Returns the key to be used in the mapped document eventually.

Returns:
		public String getMappedKey() {
			return isIdField() ?  : ;
		}

Returns whether the field references an association in case it refers to a nested field.

Returns:
		public boolean containsAssociation() {
			return false;
		}
			return null;
		}
	}

Extension of DocumentField to be backed with mapping metadata.

Author(s):
Oliver Gierke
Thomas Darimont
	protected static class MetadataBackedField extends Field {
		private static final String INVALID_ASSOCIATION_REFERENCE = "Invalid path reference %s! Associations can only be pointed to directly or via their id property!";
		private final MongoPersistentEntity<?> entity;
Creates a new MetadataBackedField with the given name, MongoPersistentEntity and MappingContext.

Parameters:
name must not be null or empty.
entity must not be null.
context must not be null.
			super(name);
			Assert.notNull(entity"MongoPersistentEntity must not be null!");
			this. = entity;
			this. = context;
			this. = getPath(name);
			this. =  == null ? null : .getLeafProperty();
		}
		/*
		 * (non-Javadoc)
		 * @see org.springframework.data.mongodb.core.convert.QueryMapper.Field#with(java.lang.String)
		 */
		public MetadataBackedField with(String name) {
		}
		/*
		 * (non-Javadoc)
		 * @see org.springframework.data.mongodb.core.convert.QueryMapper.Field#isIdKey()
		 */
		public boolean isIdField() {
			if (idProperty != null) {
				return idProperty.getName().equals() || idProperty.getFieldName().equals();
			}
		}
		/* 
		 * (non-Javadoc)
		 * @see org.springframework.data.mongodb.core.convert.QueryMapper.Field#getProperty()
		 */
			return  == null ?  : .getInverse();
		}
		/* 
		 * (non-Javadoc)
		 * @see org.springframework.data.mongodb.core.convert.QueryMapper.Field#getEntity()
		 */
			return property == null ? null : .getPersistentEntity(property);
		}
		/* 
		 * (non-Javadoc)
		 * @see org.springframework.data.mongodb.core.convert.QueryMapper.Field#isAssociation()
		 */
		public boolean isAssociation() {
			return  != null;
		}
		/* 
		 * (non-Javadoc)
		 * @see org.springframework.data.mongodb.core.convert.QueryMapper.Field#getAssociation()
		 */
			return ;
		}

Finds the association property in the PersistentPropertyPath.

Returns:
			if (this. != null) {
				for (MongoPersistentProperty p : this.) {
					if (p.isAssociation()) {
						return p.getAssociation();
					}
				}
			}
			return null;
		}
		/*
		 * (non-Javadoc)
		 * @see org.springframework.data.mongodb.core.convert.QueryMapper.Field#getTargetKey()
		 */
		public String getMappedKey() {
			return  == null ?  : .toDotPath(getPropertyConverter());
		}
			return ;
		}

Returns the PersistentPropertyPath for the given pathExpression.

Parameters:
pathExpression
Returns:
			try {
				PropertyPath path = PropertyPath.from(pathExpression.getTypeInformation());
				Iterator<MongoPersistentPropertyiterator = propertyPath.iterator();
				boolean associationDetected = false;
				while (iterator.hasNext()) {
					MongoPersistentProperty property = iterator.next();
					if (property.isAssociation()) {
						associationDetected = true;
						continue;
					}
					if (associationDetected && !property.isIdProperty()) {
						throw new MappingException(String.format(pathExpression));
					}
				}
				return propertyPath;
				return null;
			}
		}

Return the Converter to be used to created the mapped key. Default implementation will use PropertyToFieldNameConverter.

Returns:
		}
	}
New to GrepCode? Check out our FAQ X