List of usage examples for com.mongodb MongoClient getDB
@Deprecated public DB getDB(final String dbName)
From source file:at.ac.tuwien.dsg.smartcom.services.dao.MongoDBMessageInfoDAO.java
License:Apache License
/** * Create a new MongoDB message info DAO providing an already created client for a MongoDB instance, * the name of the database and a collection that should be used to save, retrieve and delete * entries.//ww w. j a v a2s. c o m * * This constructor is especially useful for unit testing because data can be preloaded in the * specified collection or the presence of added entries can be checked. * * @param client MongoClient that is connected to a database * @param database name of the database that should be used * @param collection name of the collection that should be used */ public MongoDBMessageInfoDAO(MongoClient client, String database, String collection) { coll = client.getDB(database).getCollection(collection); }
From source file:bank_server.Bank_Server.java
public static void main(String[] args) throws IOException { int PORT = 0; int POOL_SIZE = 0; int MAX_POOL_SIZE = 0; int KEEP_ALIVE = 0; // <editor-fold defaultstate="collapsed" desc="Init Properties"> /*/* w w w. j av a 2 s . co m*/ try { Properties prop = new Properties(); FileOutputStream fos = new FileOutputStream("Bank_Serveur.properties"); prop.setProperty("port", "7300"); prop.setProperty("poolSize", "3"); prop.setProperty("maxPoolSize", "5"); prop.setProperty("keepAlive", "10"); prop.store(fos, null); } catch(Exception ex){} */ // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Load Properties"> try { Properties prop = new Properties(); FileInputStream fis = new FileInputStream("Bank_Serveur.properties"); prop.load(fis); PORT = Integer.parseInt(prop.getProperty("port", "7300")); POOL_SIZE = Integer.parseInt(prop.getProperty("poosSize", "3")); MAX_POOL_SIZE = Integer.parseInt(prop.getProperty("maxPoolSize", "5")); KEEP_ALIVE = Integer.parseInt(prop.getProperty("keepAlive", "10")); fis.close(); } catch (IOException ex) { Logger.getLogger(Bank_Server.class.getName()).log(Level.SEVERE, null, ex); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Connexion DB"> DBCollection collection = null; try { MongoClient mongoClient = new MongoClient("10.43.14.40"); DB db = mongoClient.getDB("java"); collection = db.getCollection("transactions"); } catch (UnknownHostException ex) { Logger.getLogger(Bank_Server.class.getName()).log(Level.SEVERE, null, ex); } // </editor-fold> Main2 thread = new Main2(collection); thread.start(); Pool threads = new Pool(POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE); SSLServerSocket sSock = SSL.getSSLServerSocket(PORT); while (true) { SSLSocket cSock = (SSLSocket) sSock.accept(); threads.pool.execute(new Task(cSock, collection)); } }
From source file:bhl.pages.database.MongoConnection.java
License:Open Source License
/** * Connect to the database//from w ww . j a v a2 s . com * @throws Exception */ private void connect() throws Exception { if (db == null) { MongoClient mongoClient = new MongoClient(host, MONGO_PORT); db = mongoClient.getDB(this.databaseName); //boolean auth = db.authenticate( user, password.toCharArray() ); //if ( !auth ) // throw new DbException( "MongoDB authentication failed"); } }
From source file:bom.BOM.java
/** * @param args the command line arguments *///from w ww . j av a2s . c o m public static void main(String[] args) { // TODO code application logic here try { MongoClient mongoClient = new MongoClient("localhost", 5000); // Now connect to your databases //mongod --port 5000 --dbpath D:\mongodbdata\ (please mention above created path) //mongo --port 5000 DB db = mongoClient.getDB("bomdb"); System.out.println("Connect to database successfully"); //DBCollection col1 = db.createCollection("Parts",p1); DBCollection col2 = db.getCollection("BOM"); System.out.println("Collection created successfully"); List<BillOfMaterial> list; LocalDataSource ds = new LocalDataSource(); list = ds.LoadBom(1000); // To connect to mongodb server for (BillOfMaterial Element : list) { for (Parts ElementPart : Element.partList) { for (Operation ElementOp : ElementPart.optList) { BasicDBObject doc = new BasicDBObject("BOM_Name", Element.getBOM_Name()) .append("Level", Element.getLevel()).append("Stock", Element.getStock()). append("Parts", new BasicDBObject("Part_ID", ElementPart.getPart_ID()) .append("Part_Name", ElementPart.getPart_Name()) .append("Diameter", ElementPart.getDiamter()) .append("Dept", ElementPart.getDept()).append("Area", ElementPart.getArea()) .append("Quantity", ElementPart.getQuantity()). append("Material", new BasicDBObject("Material_ID", ElementPart.getMaterial_ID()) .append("Material_Name", ElementPart.getMaterial_Name()). append("Operation", new BasicDBObject("Operation_ID", ElementOp.getOperation_ID()) .append("Operation_Name", ElementOp.getOperation_Name()) .append("Equipment_Name", ElementOp.getEquipment_Name()) .append("No_of_Staff", ElementOp.getNo_of_Staff()) .append("Operation_Time", ElementOp .getOperation_Time() .get(Calendar.MINUTE) * ElementOp.getOperation_Time() .get(Calendar.SECOND)) .append("Assembly_Time", ElementOp .getAssembly_Time() .get(Calendar.MINUTE) * ElementOp.getAssembly_Time() .get(Calendar.SECOND)) .append("Set_Up_Time", ElementOp .getSet_Up_Time() .get(Calendar.MINUTE) * ElementOp.getSet_Up_Time() .get(Calendar.SECOND)) . append("Contractor", new BasicDBObject( "Contractor_ID", ElementOp.getContractor_ID()) .append("Contractor_Name", ElementOp .getContractor_Name()))))); col2.insert(doc); } } } System.out.println("Document inserted successfully"); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } }
From source file:br.bireme.scl.BrokenLinks.java
License:Open Source License
public static int createLinks(final String outCheckFile, final String outEncoding, final String mstName, final String mstEncoding, final String host, final int port, final String user, final String password, final boolean clearCol, final String[] allowedMessages) throws BrumaException, IOException { if (outCheckFile == null) { throw new NullPointerException("outCheckFile"); }//from w ww. j a va2 s .c o m if (outEncoding == null) { throw new NullPointerException("outEncoding"); } if (mstName == null) { throw new NullPointerException("mstName"); } if (mstEncoding == null) { throw new NullPointerException("mstEncoding"); } if (host == null) { throw new NullPointerException("host"); } if (port <= 0) { throw new IllegalArgumentException("port <= 0"); } if (allowedMessages == null) { throw new NullPointerException("allowedMessages"); } final Master mst = MasterFactory.getInstance(mstName).setEncoding(mstEncoding).open(); final String mName = new File(mst.getMasterName()).getName(); final BufferedReader in = new BufferedReader( new InputStreamReader(new FileInputStream(outCheckFile), outEncoding)); final MongoClient mongoClient = new MongoClient(host, port); final DB db = mongoClient.getDB(SOCIAL_CHECK_DB); // map -> mfn -> url,occ final Map<Integer, Map<String, Integer>> occMap = new HashMap<Integer, Map<String, Integer>>(); final boolean checkPassword = false; if (checkPassword) { final boolean auth = db.authenticate(user, password.toCharArray()); if (!auth) { throw new IllegalArgumentException("invalid user/password"); } } final DBCollection coll = db.getCollection(BROKEN_LINKS_COL); final DBCollection ccColl = db.getCollection(CC_FIELDS_COL); final DBCollection hColl = db.getCollection(HISTORY_COL); if (ccColl.findOne() == null) { if (!createCcFieldsCollection(ccColl)) { throw new IOException("CC fields collection creation failed"); } } final int idTag = getIsisIdField(mName, ccColl); final int urlTag = getIsisUrlFields(mName, ccColl); if (urlTag <= 0) { throw new IOException("Missing Isis url fields"); } final List<Integer> tags = getIsisCcFields(mName, ccColl); final Set<String> allowedMess = new HashSet<String>(Arrays.asList(allowedMessages)); final Map<String, Integer> idMap = getIdMfn(mst, idTag); int tell = 0; int tot = 0; if (clearCol) { coll.dropIndexes(); coll.remove(new BasicDBObject()); } System.out.println("Saving documents ..."); while (true) { final String line = in.readLine(); if (line == null) { break; } final String lineT = line.trim(); if (!lineT.isEmpty()) { final String[] split = lineT.split(" *\\| *", 4); //id|url|msg|master if (split.length < 4) { throw new IOException("Wrong line format: " + line); } final int openPos = split[2].indexOf('('); // cut extra data final String prefix = (openPos > 0) ? split[2].substring(0, openPos) : split[2]; if (allowedMess.contains(prefix.trim())) { final Integer id = idMap.get(split[0]); if (id == null) { throw new IOException("id[" + split[0] + "] not found"); } final String url_e = EncDecUrl.encodeUrl(split[1], outEncoding, false); saveRecord(mName, id, url_e, split[2], urlTag, tags, mst, coll, hColl, occMap); tot++; } if (++tell % 5000 == 0) { System.out.println("++" + tell); } } } System.out.print("\nFixing urls that do not start with http:// ... "); MongoOperations.fixMissingHttp(coll, hColl); System.out.println(" - OK"); //removeOldDocs(coll); if (clearCol) { createIndex(coll); } in.close(); mst.close(); return tot; }
From source file:br.bireme.scl.CopyMongoDb.java
License:Open Source License
private static void copyDB(final String from_host, final String to_host, final String from_db, final String to_db, final String from_port, final String to_port, final boolean appendCollections, final boolean displayAllIds) throws UnknownHostException, IOException { assert from_host != null; assert to_host != null; assert from_db != null; assert to_db != null; assert from_port != null; assert to_port != null; final int MAX_LOOP_SIZE = 15000; // MongoException$CursorNotFound final MongoClient fromClient = new MongoClient(from_host, Integer.parseInt(from_port)); final MongoClient toClient = new MongoClient(to_host, Integer.parseInt(to_port)); final DB fromDb = fromClient.getDB(from_db); final DB toDb = toClient.getDB(to_db); if (!appendCollections) { toDb.dropDatabase();/*from www. j a va 2s . c o m*/ } final Set<String> colls = fromDb.getCollectionNames(); for (String cname : colls) { if (cname.equals("system.indexes")) { continue; } final DBCollection fromColl = fromDb.getCollection(cname); final DBCollection toColl = toDb.getCollection(cname); DBCursor cursor = fromColl.find(); int curr = 0; System.out.println("Copying collection: " + cname); while (cursor.hasNext()) { if (curr % MAX_LOOP_SIZE == 0) { if (curr > 0) { cursor.close(); cursor = fromColl.find().skip(curr); if (!cursor.hasNext()) { throw new IOException("hasNext() failed"); } } } final DBObject doc = cursor.next(); final WriteResult ret = toColl.save(doc, WriteConcern.ACKNOWLEDGED); if (!ret.getCachedLastError().ok()) { System.err.println("write error doc id=" + doc.get("_id")); } if (++curr % 1000 == 0) { System.out.println("+++" + curr); } if (displayAllIds) { System.out.println(" id=" + doc.get("_id")); } } cursor.close(); System.out.println(); } }
From source file:br.bireme.scl.Gizmo.java
License:Open Source License
Collection<Element> loadRecords(final String host, final int port, final String user, final String password) throws IOException { assert host != null; assert port > 0; final MongoClient mongoClient = new MongoClient(host, port); final DB db = mongoClient.getDB(SOCIAL_CHECK_DB); if ((user != null) && (!user.trim().isEmpty())) { final boolean auth = db.authenticate(user, password.toCharArray()); if (!auth) { throw new IllegalArgumentException("invalid user/password"); }/*from w ww . j a v a 2s . c om*/ } final DBCollection coll = db.getCollection(HISTORY_COL); final String fldName = ELEM_LST_FIELD + ".0." + EXPORTED_FIELD; final BasicDBObject query = new BasicDBObject(fldName, false); final DBCursor cursor = coll.find(query); final Collection<Element> col = getNotExportedElements(coll, cursor); cursor.close(); return col; }
From source file:br.bireme.scl.JoinTitle.java
License:Open Source License
public JoinTitle(final String host, final int port) throws UnknownHostException { if (host == null) { throw new NullPointerException("host"); }/*from ww w . j a va 2 s. co m*/ if (port <= 0) { throw new IllegalArgumentException("port <= 0"); } final MongoClient mongoClient = new MongoClient(host, port); mongoClient.dropDatabase(DB_NAME); db = mongoClient.getDB(DB_NAME); }
From source file:br.bireme.scl.MongoOperations.java
License:Open Source License
public static void main(final String[] args) throws UnknownHostException, IOException { final MongoClient mongoClient = new MongoClient("ts01vm.bireme.br"); final DB db = mongoClient.getDB(SOCIAL_CHECK_DB); final DBCollection coll = db.getCollection(BROKEN_LINKS_COL); final DBCollection hcoll = db.getCollection(HISTORY_COL); final Set<String> centers = getCenters(coll); for (String center : centers) { System.out.println(center); }/* ww w . j a v a2s . c o m*/ System.out.println(); /*final List<IdUrl> ius = getCenterUrls(coll, "PE1.1"); for (IdUrl iu : ius) { System.out.println("1) " + iu.id + " " + iu.url); } final Set<IdUrl> rel = fixRelatedUrls(coll, hcoll, "Heitor", "PE1.1", //"xhttp://new.paho.org/bireme/index.php?Itemid=43&lang=pt", //"http://new.paho.org/bireme/index.php?Itemid=43&lang=pt"); //"http://new.paho.org/bireme/indexx.php?Itemid=43&lang=pt", //"http://new.paho.org/bireme/index.php?Itemid=43&lang=pt"); "http://new.paho.org/bireme/indexx.php?Itemid=43&lang=xpt", "http://new.paho.org/bireme/index.php?Itemid=43&lang=pt"); //"http://new.paho.org/bireme/index.php?Itemid=43&lang=xpt", //"http://new.paho.org/bireme/index.php?Itemid=43&lang=pt"); for (IdUrl iu : rel) { System.out.println("2) " + iu.id + " " + iu.url); }*/ }
From source file:br.bireme.scl.ResetExportFlag.java
License:Open Source License
private static void reset(final String host, final int port, final String database, final String collection, final String sdate) throws UnknownHostException, ParseException { assert host != null; assert port > 0; assert database != null; assert collection != null; final MongoClient client = new MongoClient(host, port); final DB db = client.getDB(database); final DBCollection coll = db.getCollection(collection); final String prefix = ELEM_LST_FIELD + ".0."; final BasicDBObject query; final DBCursor cursor; if (sdate == null) { query = new BasicDBObject(prefix + EXPORTED_FIELD, true); } else {// w ww. j a v a 2s.co m final SimpleDateFormat simple = new SimpleDateFormat("yyyyMMdd"); final Date date = simple.parse(sdate); final BasicDBList list = new BasicDBList(); list.add(new BasicDBObject(prefix + EXPORTED_FIELD, true)); list.add(new BasicDBObject(prefix + LAST_UPDATE_FIELD, new BasicDBObject("$gte", date))); query = new BasicDBObject("$and", list); } cursor = coll.find(query); while (cursor.hasNext()) { final BasicDBObject doc = (BasicDBObject) cursor.next(); final BasicDBList list = (BasicDBList) doc.get(ELEM_LST_FIELD); final BasicDBObject elem = (BasicDBObject) list.get(0); elem.put(EXPORTED_FIELD, false); coll.save(doc); } cursor.close(); }