PageRenderTime 52ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 0ms

/src/com/edgytech/umongo/MongoUtils.java

https://github.com/agirbal/umongo
Java | 271 lines | 208 code | 26 blank | 37 comment | 72 complexity | 99106ef0908f455c31f7ae5fb697173b MD5 | raw file
  1. /**
  2. * Copyright (C) 2010 EdgyTech LLC.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.edgytech.umongo;
  17. import com.google.gson.Gson;
  18. import com.google.gson.GsonBuilder;
  19. import com.google.gson.JsonParser;
  20. import com.mongodb.*;
  21. import com.mongodb.util.JSONSerializers;
  22. import com.mongodb.util.ObjectSerializer;
  23. import java.util.Date;
  24. import java.util.Map;
  25. import javax.swing.tree.DefaultMutableTreeNode;
  26. import org.bson.LazyDBList;
  27. import org.bson.types.BSONTimestamp;
  28. import org.bson.types.ObjectId;
  29. /**
  30. *
  31. * @author antoine
  32. */
  33. public class MongoUtils {
  34. public static String queryOptionsToString(int options) {
  35. String opt = "";
  36. if ((options & Bytes.QUERYOPTION_TAILABLE) != 0) {
  37. opt += "TAILABLE ";
  38. }
  39. if ((options & Bytes.QUERYOPTION_SLAVEOK) != 0) {
  40. opt += "SLAVEOK ";
  41. }
  42. if ((options & Bytes.QUERYOPTION_OPLOGREPLAY) != 0) {
  43. opt += "OPLOGREPLAY ";
  44. }
  45. if ((options & Bytes.QUERYOPTION_NOTIMEOUT) != 0) {
  46. opt += "NOTIMEOUT ";
  47. }
  48. if ((options & Bytes.QUERYOPTION_AWAITDATA) != 0) {
  49. opt += "AWAITDATA ";
  50. }
  51. if ((options & Bytes.QUERYOPTION_EXHAUST) != 0) {
  52. opt += "EXHAUST ";
  53. }
  54. return opt;
  55. }
  56. public static void addChildrenToTreeNode(DefaultMutableTreeNode node, DBObject obj) {
  57. for (String key : obj.keySet()) {
  58. Object val = obj.get(key);
  59. // if (val == null) {
  60. // continue;
  61. // }
  62. DefaultMutableTreeNode child = new DefaultMutableTreeNode(new TreeNodeDocumentField(key, val));
  63. if (val instanceof DBObject) {
  64. addChildrenToTreeNode(child, (DBObject) val);
  65. } else if (val instanceof ObjectId) {
  66. // break it down
  67. ObjectId id = (ObjectId) val;
  68. child.add(new DefaultMutableTreeNode("Time: " + id.getTime() + " = " + new Date(id.getTime()).toString()));
  69. child.add(new DefaultMutableTreeNode("Machine: " + (id.getMachine() & 0xFFFFFFFFL)));
  70. child.add(new DefaultMutableTreeNode("Inc: " + (id.getInc() & 0xFFFFFFFFL)));
  71. }
  72. node.add(child);
  73. }
  74. }
  75. public static String getObjectString(Object obj) {
  76. return getObjectString(obj, 0);
  77. }
  78. public static String getObjectString(Object obj, int limit) {
  79. String str;
  80. if (obj == null) {
  81. str = "null";
  82. } else if (obj instanceof DBObject || obj instanceof byte[]) {
  83. // get rid of annoying scientific format
  84. str = MongoUtils.getJSON(obj);
  85. } else if (obj instanceof Double) {
  86. // get rid of annoying scientific format
  87. str = String.format("%f", obj);
  88. } else if (obj instanceof String) {
  89. // should show quotes to be JSON like
  90. str = "\"" + obj + "\"";
  91. } else {
  92. str = obj.toString();
  93. }
  94. return limitString(str, limit);
  95. }
  96. public static String limitString(String str, int limit) {
  97. if (limit <= 0) {
  98. limit = UMongo.instance.getPreferences().getInlineDocumentLength();
  99. }
  100. if (str.length() > limit && limit > 0) {
  101. int max = Math.max(0, limit - 3);
  102. str = str.substring(0, max) + " ..";
  103. }
  104. return str;
  105. }
  106. static ObjectSerializer getSerializer() {
  107. return JSONSerializers.getStrict();
  108. }
  109. static String getJSONPreview(Object value) {
  110. return MongoUtils.limitString(getSerializer().serialize(value), 80);
  111. }
  112. static String getJSON(Object value) {
  113. return getSerializer().serialize(value);
  114. }
  115. public static DBObject getReplicaSetInfo(MongoClient mongo) {
  116. DB db = mongo.getDB("local");
  117. DBObject result = new BasicDBObject();
  118. DBCollection namespaces = db.getCollection("system.namespaces");
  119. String oplogName;
  120. if (namespaces.findOne(new BasicDBObject("name", "local.oplog.rs")) != null) {
  121. oplogName = "oplog.rs";
  122. } else if (namespaces.findOne(new BasicDBObject("name", "local.oplog.$main")) != null) {
  123. oplogName = "oplog.$main";
  124. } else {
  125. return null;
  126. }
  127. DBObject olEntry = namespaces.findOne(new BasicDBObject("name", "local." + oplogName));
  128. if (olEntry != null && olEntry.containsField("options")) {
  129. BasicDBObject options = (BasicDBObject) olEntry.get("options");
  130. long size = options.getLong("size");
  131. result.put("logSizeMB", Float.valueOf(String.format("%.2f", size / 1048576f)));
  132. } else {
  133. return null;
  134. }
  135. DBCollection oplog = db.getCollection(oplogName);
  136. int size = oplog.getStats().getInt("size");
  137. result.put("usedMB", Float.valueOf(String.format("%.2f", size / 1048576f)));
  138. DBCursor firstc = oplog.find().sort(new BasicDBObject("$natural", 1)).limit(1);
  139. DBCursor lastc = oplog.find().sort(new BasicDBObject("$natural", -1)).limit(1);
  140. if (!firstc.hasNext() || !lastc.hasNext()) {
  141. return null;
  142. }
  143. BasicDBObject first = (BasicDBObject) firstc.next();
  144. BasicDBObject last = (BasicDBObject) lastc.next();
  145. BSONTimestamp tsfirst = (BSONTimestamp) first.get("ts");
  146. BSONTimestamp tslast = (BSONTimestamp) last.get("ts");
  147. if (tsfirst == null || tslast == null) {
  148. return null;
  149. }
  150. int ftime = tsfirst.getTime();
  151. int ltime = tslast.getTime();
  152. int timeDiffSec = ltime - ftime;
  153. result.put("timeDiff", timeDiffSec);
  154. result.put("timeDiffHours", Float.valueOf(String.format("%.2f", timeDiffSec / 3600f)));
  155. result.put("tFirst", new Date(ftime * 1000l));
  156. result.put("tLast", new Date(ltime * 1000l));
  157. result.put("now", new Date());
  158. return result;
  159. }
  160. public static boolean isBalancerOn(MongoClient mongo) {
  161. final DB config = mongo.getDB("config");
  162. final DBCollection settings = config.getCollection("settings");
  163. BasicDBObject res = (BasicDBObject) settings.findOne(new BasicDBObject("_id", "balancer"));
  164. if (res == null || !res.containsField("stopped"))
  165. return true;
  166. return !res.getBoolean("stopped");
  167. }
  168. static String makeInfoString(Object ... args) {
  169. String info = "";
  170. for (int i = 0; i < args.length; i += 2) {
  171. if (i > 0)
  172. info += ", ";
  173. info += args[i] + "=[" + args[i + 1] + "]";
  174. }
  175. return info;
  176. }
  177. public static DBObject checkObject( DBObject o , boolean canBeNull , boolean query ){
  178. if ( o == null ){
  179. if ( canBeNull )
  180. return null;
  181. throw new IllegalArgumentException( "can't be null" );
  182. }
  183. if ( o.isPartialObject() && ! query )
  184. throw new IllegalArgumentException( "can't save partial objects" );
  185. if ( ! query ){
  186. checkKeys(o);
  187. }
  188. return o;
  189. }
  190. /**
  191. * Checks key strings for invalid characters.
  192. */
  193. public static void checkKeys( DBObject o ) {
  194. if ( o instanceof LazyDBObject || o instanceof LazyDBList )
  195. return;
  196. for ( String s : o.keySet() ){
  197. validateKey ( s );
  198. Object inner = o.get( s );
  199. if ( inner instanceof DBObject ) {
  200. checkKeys( (DBObject)inner );
  201. } else if ( inner instanceof Map ) {
  202. checkKeys( (Map<String, Object>)inner );
  203. }
  204. }
  205. }
  206. /**
  207. * Checks key strings for invalid characters.
  208. */
  209. public static void checkKeys( Map<String, Object> o ) {
  210. for ( String s : o.keySet() ){
  211. validateKey ( s );
  212. Object inner = o.get( s );
  213. if ( inner instanceof DBObject ) {
  214. checkKeys( (DBObject)inner );
  215. } else if ( inner instanceof Map ) {
  216. checkKeys( (Map<String, Object>)inner );
  217. }
  218. }
  219. }
  220. /**
  221. * Check for invalid key names
  222. * @param s the string field/key to check
  223. * @exception IllegalArgumentException if the key is not valid.
  224. */
  225. public static void validateKey(String s ) {
  226. if ( s.contains( "." ) )
  227. throw new IllegalArgumentException( "fields stored in the db can't have . in them. (Bad Key: '" + s + "')" );
  228. if ( s.startsWith( "$" ) )
  229. throw new IllegalArgumentException( "fields stored in the db can't start with '$' (Bad Key: '" + s + "')" );
  230. }
  231. private static JsonParser jsonParser;
  232. public static JsonParser getJsonParser() {
  233. if (jsonParser == null) {
  234. jsonParser = new JsonParser();
  235. }
  236. return jsonParser;
  237. }
  238. private static Gson gson;
  239. public static Gson getGson() {
  240. if (gson == null) {
  241. gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
  242. }
  243. return gson;
  244. }
  245. }