1 package wrappers; 2 3 import java.util.Date; 4 import java.util.List; 5 import java.util.Set; 6 7 import com.mongodb.AggregationOptions; 8 import com.mongodb.BasicDBList; 9 import com.mongodb.BasicDBObject; 10 import com.mongodb.Cursor; 11 import com.mongodb.DB; 12 import com.mongodb.DBCollection; 13 import com.mongodb.DBObject; 14 import com.mongodb.MongoClient; 15 import com.mongodb.MongoClientURI; 16 import com.mongodb.MongoException; 17 import com.mongodb.WriteConcernException; 18 import com.mongodb.WriteResult; 19 import com.mongodb.util.JSON; 20 21 public class Mongo2Interface { 22 boolean DEBUG = false; 23 String Errmsg = "No error"; 24 String ovalName = null; 25 Set<String> Colnames = null; 26 Cursor cursor = null; 27 MongoClient client = null; 28 DB db = null; 29 DBCollection coll = null; 30 BasicDBObject doc = null; 31 BasicDBObject dbq = null; 32 BasicDBObject dbf = null; 33 List<DBObject> pip = null; 34 AggregationOptions aop = null; 35 36 // === Constructors/finalize ========================================= Mongo2Interface()37 public Mongo2Interface() { 38 this(false); 39 } // end of default constructor 40 Mongo2Interface(boolean b)41 public Mongo2Interface(boolean b) { 42 DEBUG = b; 43 } // end of constructor 44 SetErrmsg(String str)45 protected void SetErrmsg(String str) { 46 if (DEBUG) 47 System.out.println(str); 48 49 Errmsg = str; 50 } // end of SetErrmsg 51 SetErrmsg(Exception e)52 protected void SetErrmsg(Exception e) { 53 if (DEBUG) 54 System.out.println(e.getMessage()); 55 56 Errmsg = e.toString(); 57 } // end of SetErrmsg 58 GetErrmsg()59 public String GetErrmsg() { 60 String err = Errmsg; 61 62 Errmsg = "No error"; 63 return err; 64 } // end of GetErrmsg 65 MongoConnect(String[] parms)66 public int MongoConnect(String[] parms) { 67 int rc = 0; 68 69 if (DEBUG) 70 System.out.println("Mongo2: URI=" + parms[0] + " DB=" + parms[1]); 71 72 try { 73 MongoClientURI uri = new MongoClientURI(parms[0]); 74 75 client = new MongoClient(uri); 76 77 if (DEBUG) 78 System.out.println("Connection " + client.toString() + " established"); 79 80 // Now connect to your databases 81 db = client.getDB(parms[1]); 82 83 if (parms[2] != null && !parms[2].isEmpty()) { 84 if (DEBUG) 85 System.out.println("user=" + parms[2] + " pwd=" + parms[3]); 86 87 @SuppressWarnings("deprecation") 88 boolean auth = db.authenticate(parms[2], parms[3].toCharArray()); 89 90 if (DEBUG) 91 System.out.println("Authentication: " + auth); 92 93 } // endif user 94 95 } catch (MongoException me) { 96 SetErrmsg(me); 97 rc = -1; 98 } catch (Exception e) { 99 SetErrmsg(e); 100 rc = -3; 101 } // end try/catch 102 103 return rc; 104 } // end of MongoConnect 105 MongoDisconnect()106 public int MongoDisconnect() { 107 int rc = 0; 108 109 try { 110 if (cursor != null) { 111 if (DEBUG) 112 System.out.println("Closing cursor"); 113 114 cursor.close(); 115 cursor = null; 116 } // endif client 117 118 if (client != null) { 119 if (DEBUG) 120 System.out.println("Closing connection"); 121 122 client.close(); 123 client = null; 124 } // endif client 125 126 } catch (MongoException se) { 127 SetErrmsg(se); 128 rc += 8; 129 } // end try/catch 130 131 return rc; 132 } // end of MongoDisconnect 133 GetCollection(String name)134 public boolean GetCollection(String name) { 135 if (DEBUG) 136 System.out.println("GetCollection: name=" + name); 137 138 try { 139 coll = db.getCollection(name); 140 } catch (Exception e) { 141 SetErrmsg(e); 142 return true; 143 } // end try/catch 144 145 return false; 146 } // end of GetCollection 147 GetCollSize()148 public long GetCollSize() { 149 return (coll != null) ? coll.count() : 0; 150 } // end of GetCollSize 151 FindColl(String query, String fields)152 public boolean FindColl(String query, String fields) { 153 if (DEBUG) 154 System.out.println("FindColl: query=" + query + " fields=" + fields); 155 156 try { 157 if (query != null || fields != null) { 158 dbq = (BasicDBObject) JSON.parse((query != null) ? query : "{}"); 159 160 if (fields != null) { 161 dbf = (BasicDBObject) JSON.parse(fields); 162 cursor = coll.find(dbq, dbf); 163 } else 164 cursor = coll.find(dbq); 165 166 } else 167 cursor = coll.find(); 168 169 } catch (Exception e) { 170 SetErrmsg(e); 171 return true; 172 } // end try/catch 173 174 return false; 175 } // end of FindColl 176 177 @SuppressWarnings("unchecked") AggregateColl(String pipeline)178 public boolean AggregateColl(String pipeline) { 179 if (DEBUG) 180 System.out.println("AggregateColl: pipeline=" + pipeline); 181 182 try { 183 DBObject pipe = (DBObject) JSON.parse(pipeline); 184 185 pip = (List<DBObject>) pipe.get("pipeline"); 186 aop = AggregationOptions.builder().batchSize(0).allowDiskUse(true) 187 .outputMode(AggregationOptions.OutputMode.CURSOR).build(); 188 cursor = coll.aggregate(pip, aop); 189 } catch (MongoException me) { 190 SetErrmsg(me); 191 return true; 192 } // end try/catch 193 194 return false; 195 } // end of AggregateColl 196 Rewind()197 public boolean Rewind() { 198 if (cursor != null) 199 cursor.close(); 200 201 if (pip == null) { 202 if (dbf != null) 203 cursor = coll.find(dbq, dbf); 204 else if (dbq != null) 205 cursor = coll.find(dbq); 206 else 207 cursor = coll.find(); 208 209 } else 210 cursor = coll.aggregate(pip, aop); 211 212 return (cursor == null); 213 } // end of Rewind 214 ReadNext()215 public int ReadNext() { 216 try { 217 if (cursor.hasNext()) { 218 doc = (BasicDBObject) cursor.next(); 219 220 if (DEBUG) 221 System.out.println("Class doc = " + doc.getClass()); 222 223 Colnames = doc.keySet(); 224 return Colnames.size(); 225 } else 226 return 0; 227 228 } catch (MongoException me) { 229 SetErrmsg(me); 230 return -1; 231 } // end try/catch 232 233 } // end of ReadNext 234 Fetch(int row)235 public boolean Fetch(int row) { 236 if (cursor.hasNext()) { 237 doc = (BasicDBObject) cursor.next(); 238 Colnames = doc.keySet(); 239 return true; 240 } else 241 return false; 242 243 } // end of Fetch 244 GetDoc()245 public String GetDoc() { 246 return (doc != null) ? doc.toString() : null; 247 } // end of GetDoc 248 GetColumns()249 public Set<String> GetColumns() { 250 if (doc != null) 251 return doc.keySet(); 252 else 253 return null; 254 255 } // end of GetColumns 256 ColumnDesc(Object obj, int n, int[] val, int lvl)257 public Object ColumnDesc(Object obj, int n, int[] val, int lvl) { 258 Object ret = null; 259 Object oval = ((obj != null) ? obj : doc); 260 BasicDBObject dob = (oval instanceof BasicDBObject) ? (BasicDBObject) oval : null; 261 BasicDBList ary = (oval instanceof BasicDBList) ? (BasicDBList) oval : null; 262 263 try { 264 if (ary != null) { 265 oval = ary.get(n); 266 ovalName = Integer.toString(n); 267 } else if (dob != null) { 268 // String[] k = dob.keySet().toArray(new String[0]); 269 Object[] k = dob.keySet().toArray(); 270 oval = dob.get(k[n]); 271 ovalName = (String) k[n]; 272 } else 273 ovalName = "x" + Integer.toString(n); 274 275 if (DEBUG) 276 System.out.println("Class of " + ovalName + " = " + oval.getClass()); 277 278 val[0] = 0; // ColumnType 279 val[1] = 0; // Precision 280 val[2] = 0; // Scale 281 val[3] = 0; // Nullable 282 val[4] = 0; // ncol 283 284 if (oval == null) { 285 val[3] = 1; 286 } else if (oval instanceof String) { 287 val[0] = 1; 288 val[1] = ((String) oval).length(); 289 } else if (oval instanceof org.bson.types.ObjectId) { 290 val[0] = 1; 291 val[1] = ((org.bson.types.ObjectId) oval).toString().length(); 292 } else if (oval instanceof Integer) { 293 val[0] = 7; 294 val[1] = Integer.toString(((Integer) oval).intValue()).length(); 295 } else if (oval instanceof Long) { 296 val[0] = 5; 297 val[1] = Long.toString(((Long) oval).longValue()).length(); 298 } else if (oval instanceof Date) { 299 Long TS = (((Date) oval).getTime() / 1000); 300 val[0] = 8; 301 val[1] = TS.toString().length(); 302 } else if (oval instanceof Double) { 303 String d = Double.toString(((Double) oval).doubleValue()); 304 int i = d.indexOf('.') + 1; 305 306 val[0] = 2; 307 val[1] = d.length(); 308 val[2] = (i > 0) ? val[1] - i : 0; 309 } else if (oval instanceof Boolean) { 310 val[0] = 4; 311 val[1] = 1; 312 } else if (oval instanceof BasicDBObject) { 313 if (lvl > 0) { 314 ret = oval; 315 val[0] = 1; 316 val[4] = ((BasicDBObject) oval).size(); 317 } else if (lvl == 0) { 318 val[0] = 1; 319 val[1] = oval.toString().length(); 320 } // endif lvl 321 322 } else if (oval instanceof BasicDBList) { 323 if (lvl > 0) { 324 ret = oval; 325 val[0] = 2; 326 val[4] = ((BasicDBList) oval).size(); 327 } else if (lvl == 0) { 328 val[0] = 1; 329 val[1] = oval.toString().length(); 330 } // endif lvl 331 332 } else { 333 SetErrmsg("Type " + " of " + ovalName + " not supported"); 334 val[0] = -1; 335 } // endif's 336 337 return ret; 338 } catch (Exception ex) { 339 SetErrmsg(ex); 340 } // end try/catch 341 342 val[0] = -1; 343 return null; 344 } // end of ColumnDesc 345 ColDescName()346 public String ColDescName() { 347 return ovalName; 348 } // end of ColDescName 349 GetFieldObject(String path)350 protected Object GetFieldObject(String path) { 351 Object o = null; 352 BasicDBObject dob = null; 353 BasicDBList lst = null; 354 String[] names = null; 355 356 if (path == null || path.equals("") || path.equals("*")) 357 return doc; 358 else if (doc instanceof BasicDBObject) 359 dob = doc; 360 // else if (o instanceof BasicDBList) 361 // lst = (BasicDBList) doc; 362 else 363 return doc; 364 365 try { 366 names = path.split("\\."); 367 368 for (String name : names) { 369 if (lst != null) { 370 o = lst.get(Integer.parseInt(name)); 371 } else 372 o = dob.get(name); 373 374 if (o == null) 375 break; 376 377 if (DEBUG) 378 System.out.println("Class o = " + o.getClass()); 379 380 if (o instanceof BasicDBObject) { 381 dob = (BasicDBObject) o; 382 lst = null; 383 } else if (o instanceof BasicDBList) { 384 lst = (BasicDBList) o; 385 } else 386 break; 387 388 } // endfor name 389 390 } catch (IndexOutOfBoundsException x) { 391 o = null; 392 } catch (MongoException se) { 393 SetErrmsg(se); 394 o = null; 395 } // end try/catch 396 397 return o; 398 } // end of GetFieldObject 399 GetField(String path)400 public String GetField(String path) { 401 Object o = GetFieldObject(path); 402 403 if (o != null) { 404 if (o instanceof Date) { 405 Long TS = (((Date) o).getTime() / 1000); 406 return TS.toString(); 407 } else if (o instanceof Boolean) 408 return (Boolean) o ? "1" : "0"; 409 410 return o.toString(); 411 } else 412 return null; 413 414 } // end of GetField 415 MakeBson(String s, int json)416 public Object MakeBson(String s, int json) { 417 if (json == 1 || json == 2) { 418 return com.mongodb.util.JSON.parse(s); 419 } else 420 return null; 421 422 } // end of MakeBson 423 MakeDocument()424 public Object MakeDocument() { 425 return new BasicDBObject(); 426 } // end of MakeDocument 427 DocAdd(Object bdc, String key, Object val, int json)428 public boolean DocAdd(Object bdc, String key, Object val, int json) { 429 try { 430 if (json != 0 && val instanceof String) 431 ((BasicDBObject) bdc).append(key, JSON.parse((String) val)); 432 else 433 ((BasicDBObject) bdc).append(key, val); 434 435 } catch (MongoException me) { 436 SetErrmsg(me); 437 return true; 438 } // end try/catch 439 440 return false; 441 } // end of DocAdd 442 MakeArray()443 public Object MakeArray() { 444 return new BasicDBList(); 445 } // end of MakeArray 446 ArrayAdd(Object bar, int n, Object val, int json)447 public boolean ArrayAdd(Object bar, int n, Object val, int json) { 448 try { 449 if (json != 0 && val instanceof String) 450 ((BasicDBList) bar).put(n, JSON.parse((String) val)); 451 else 452 ((BasicDBList) bar).put(n, val); 453 454 } catch (MongoException me) { 455 SetErrmsg(me); 456 return true; 457 } catch (Exception ex) { 458 SetErrmsg(ex); 459 return true; 460 } // end try/catch 461 462 return false; 463 } // end of ArrayAdd 464 CollInsert(Object dob)465 public boolean CollInsert(Object dob) { 466 try { 467 coll.insert((BasicDBObject) dob); 468 } catch (MongoException me) { 469 SetErrmsg(me); 470 return true; 471 } catch (Exception ex) { 472 SetErrmsg(ex); 473 return true; 474 } // end try/catch 475 476 return false; 477 } // end of CollInsert 478 CollUpdate(Object upd)479 public long CollUpdate(Object upd) { 480 long n = -1; 481 482 if (DEBUG) 483 System.out.println("upd: " + upd.toString()); 484 485 try { 486 DBObject qry = new BasicDBObject("_id", doc.get("_id")); 487 488 WriteResult res = coll.update(qry, (DBObject) upd); 489 490 if (DEBUG) 491 System.out.println("CollUpdate: " + res.toString()); 492 493 n = res.getN(); 494 } catch (MongoException me) { 495 SetErrmsg(me); 496 } catch (Exception ex) { 497 SetErrmsg(ex); 498 } // end try/catch 499 500 return n; 501 } // end of CollUpdate 502 CollDelete(boolean all)503 public long CollDelete(boolean all) { 504 long n = -1; 505 506 try { 507 WriteResult res; 508 BasicDBObject qry = new BasicDBObject(); 509 510 if (!all) 511 qry.append("_id", doc.get("_id")); 512 513 res = coll.remove(qry); 514 515 if (DEBUG) 516 System.out.println("CollDelete: " + res.toString()); 517 518 n = res.getN(); 519 } catch (WriteConcernException wx) { 520 SetErrmsg(wx); 521 } catch (MongoException me) { 522 SetErrmsg(me); 523 } catch (UnsupportedOperationException ux) { 524 SetErrmsg(ux); 525 n = 0; 526 } // end try/catch 527 528 return n; 529 } // end of CollDelete 530 531 } // end of class MongoInterface 532