001/* 002 * Copyright 2001-2013 Stephen Colebourne 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.joda.beans.integrate.mongo; 017 018import java.util.Iterator; 019import java.util.Map; 020import java.util.Set; 021 022import org.joda.beans.Bean; 023 024import com.mongodb.DBObject; 025 026/** 027 * Allows a Joda-Bean to be passed directly to MongoDB. 028 * 029 * @author Stephen Colebourne 030 */ 031public class BeanMongoDBObject implements DBObject { 032 033 /** 034 * The underlying bean. 035 */ 036 private final Bean bean; 037 /** 038 * The Mongo partial flag. 039 */ 040 private boolean partial; 041 042 /** 043 * Creates an instance wrapping a bean. 044 * @param bean the bean to wrap, not null 045 */ 046 public BeanMongoDBObject(Bean bean) { 047 this.bean = bean; 048 } 049 050 //----------------------------------------------------------------------- 051 @Override 052 public boolean containsField(String name) { 053 return bean.propertyNames().contains(name); 054 } 055 056 /** 057 * {@inheritDoc} 058 * @deprecated Use containsField() 059 */ 060 @Override 061 @Deprecated 062 public boolean containsKey(String name) { 063 return containsField(name); 064 } 065 066 @Override 067 public Object get(String name) { 068 return bean.property(name).get(); 069 } 070 071 @Override 072 public Object put(String name, Object value) { 073 return bean.property(name).put(value); 074 } 075 076 @Override 077 public void putAll(DBObject object) { 078 for (String name : object.keySet()) { 079 put(name, object.get(name)); 080 } 081 } 082 083 @Override 084 @SuppressWarnings("rawtypes") 085 public void putAll(Map map) { 086 for (Iterator it = map.keySet().iterator(); it.hasNext(); ) { 087 Object key = (Object) it.next(); 088 put(key.toString(), map.get(key)); 089 } 090 } 091 092 @Override 093 public Object removeField(String name) { 094 throw new UnsupportedOperationException("Remove unsupported"); 095 } 096 097 @Override 098 public Set<String> keySet() { 099 return bean.propertyNames(); 100 } 101 102 @Override 103 @SuppressWarnings("rawtypes") 104 public Map toMap() { 105 return bean.metaBean().createPropertyMap(bean).flatten(); 106 } 107 108 //----------------------------------------------------------------------- 109 @Override 110 public boolean isPartialObject() { 111 return partial; 112 } 113 114 @Override 115 public void markAsPartialObject() { 116 partial = true; 117 } 118 119}