List of usage examples for com.mongodb MongoClient getDB
@Deprecated public DB getDB(final String dbName)
From source file:fr.ensimag.biblio.dao.impl.MongoDBUserDAO.java
public MongoDBUserDAO(MongoClient mongo) { this.col = mongo.getDB("MyWebAppDB").getCollection("Users"); }
From source file:fr.gouv.vitam.mdbes.MongoDbAccess.java
License:Open Source License
/** * * @param mongoClient/*from w ww . j a v a 2 s . c o m*/ * the current valid MongoClient to use as connector to the database * @param dbname * the MongoDB database name * @param esname * the ElasticSearch name * @param unicast * the unicast addresses for ElasticSearch * @param recreate * shall we recreate the index * @throws InvalidUuidOperationException */ @SuppressWarnings("unused") public MongoDbAccess(final MongoClient mongoClient, final String dbname, final String esname, final String unicast, final boolean recreate) throws InvalidUuidOperationException { db = mongoClient.getDB(dbname); dbadmin = mongoClient.getDB("admin"); // Authenticate - optional // boolean auth = db.authenticate("foo", "bar"); collections = new VitamCollection[VitamCollections.values().length]; // get a collection object to work with domains = collections[VitamCollections.Cdomain.rank] = new VitamCollection(db, VitamCollections.Cdomain, recreate); daips = collections[VitamCollections.Cdaip.rank] = new VitamCollection(db, VitamCollections.Cdaip, recreate); paips = collections[VitamCollections.Cpaip.rank] = new VitamCollection(db, VitamCollections.Cpaip, recreate); saips = collections[VitamCollections.Csaip.rank] = new VitamCollection(db, VitamCollections.Csaip, recreate); duarefs = collections[VitamCollections.Cdua.rank] = new VitamCollection(db, VitamCollections.Cdua, recreate); if (GlobalDatas.USELRUCACHE || GlobalDatas.USEREDIS) { requests = null; collections[VitamCollections.Crequests.rank] = null; } else { requests = collections[VitamCollections.Crequests.rank] = new VitamCollection(db, VitamCollections.Crequests, recreate); } final DBCursor cursor = domains.collection.find(); for (final DBObject dbObject : cursor) { final Domain dom = (Domain) dbObject; dom.setRoot(); } // elasticsearch index LOGGER.info("ES on cluster name: " + esname + ":" + unicast); es = new ElasticSearchAccess(esname, unicast, GlobalDatas.localNetworkAddress); try { md = MessageDigest.getInstance("SHA-512"); } catch (NoSuchAlgorithmException e) { LOGGER.error(e); } if (GlobalDatas.USEREDIS) { ra = new RedisAccess(unicast, 20); } }
From source file:fr.imag.unql.transformation.util.MongoDBUtil.java
License:Open Source License
@Override public String executeQuery(final String relationName, final String connectionURL, final String connectionUsername, final String connectionPassword, final List<String> attributes, final List<String> conditions) { DB database;/*from w w w .ja va 2 s. co m*/ DBCursor queryResults; DBCollection collection; MongoClient mongoClient; StringBuilder returnValue; BasicDBObject searchQuery; BasicDBObject searchAttributes; returnValue = new StringBuilder(); Map<String, String> conditionsMap; Map<String, String> attributesMap; try { searchQuery = new BasicDBObject(); searchAttributes = new BasicDBObject(); mongoClient = new MongoClient(connectionURL); database = mongoClient.getDB(relationName); // Database connection if ((connectionUsername != null) && (connectionPassword != null)) { database.authenticate(connectionUsername, connectionPassword.toCharArray()); } // Format attributes that will be projected attributesMap = this.getAttributesMap(relationName, attributes); for (String key : attributesMap.keySet()) { searchAttributes.put(key, attributesMap.get(key)); } // Format conditions that will be applied conditionsMap = this.getConditionsMap(relationName, conditions); for (String key : conditionsMap.keySet()) { searchQuery.put(key, conditionsMap.get(key)); } // Execute query and retrieve results collection = database.getCollection(relationName); queryResults = collection.find(searchQuery, searchAttributes); while (queryResults.hasNext()) { returnValue.append(queryResults.next()).append("\n"); } } catch (Exception e) { returnValue.append("Error while executing MongoDB query: " + e.getMessage()); } return returnValue.toString(); }
From source file:generate.MapGenerateAction.java
@Override public String execute() { String file_path = "/home/chanakya/NetBeansProjects/Concepto/UploadedFiles"; try {// w w w .j a v a 2 s . c om File fileToCreate = new File(file_path, concept_map.getUploadedFileFileName()); FileUtils.copyFile(concept_map.getUploadedFile(), fileToCreate); } catch (Throwable t) { System.out.println("E1: " + t.getMessage()); return ERROR; } try { List<String> temp_text = FileUtils.readLines(concept_map.getUploadedFile()); StringBuilder text = new StringBuilder(); for (String s : temp_text) { text.append(s); } concept_map.setInput_text(text.toString()); } catch (IOException e) { //e.printStackTrace(); System.out.println("E2: " + e.getMessage()); return ERROR; } String temp_filename = concept_map.getUploadedFileFileName().split("\\.(?=[^\\.]+$)")[0]; temp_filename = temp_filename.trim(); try { String temp = "java -jar /home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCore.jar " + file_path + " " + temp_filename; System.out.println(temp); File jarfile = new File("/home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCore.jar"); JarFile jar = new JarFile(jarfile); Manifest manifest = jar.getManifest(); Attributes attrs = manifest.getMainAttributes(); String mainClassName = attrs.getValue(Attributes.Name.MAIN_CLASS); System.out.println(mainClassName); URL url = new URL("file", null, jarfile.getAbsolutePath()); ClassLoader cl = new URLClassLoader(new URL[] { url }); Class mainClass = cl.loadClass(mainClassName); Method mainMethod = mainClass.getMethod("main", new Class[] { String[].class }); String[] args = new String[2]; args[0] = file_path; args[1] = temp_filename; System.out.println(args[0]); System.out.println(args[1]); try { mainMethod.invoke(mainClass, new Object[] { args }); } catch (InvocationTargetException e) { System.out.println("This is the exception: " + e.getTargetException().toString()); } } catch (IllegalArgumentException | IllegalAccessException | NoSuchMethodException | ClassNotFoundException | IOException e) { System.out.println("E3: " + e.getMessage()); return ERROR; } try { String temp2 = "java -jar /home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCoreII.jar " + file_path + " " + temp_filename; System.out.println(temp2); File jarfile = new File("/home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCoreII.jar"); JarFile jar = new JarFile(jarfile); Manifest manifest = jar.getManifest(); Attributes attrs = manifest.getMainAttributes(); String mainClassName = attrs.getValue(Attributes.Name.MAIN_CLASS); System.out.println(mainClassName); URL url = new URL("file", null, jarfile.getAbsolutePath()); ClassLoader cl = new URLClassLoader(new URL[] { url }); Class mainClass = cl.loadClass(mainClassName); Method mainMethod = mainClass.getMethod("main", new Class[] { String[].class }); String[] args = new String[2]; args[0] = file_path; args[1] = temp_filename; mainMethod.invoke(mainClass, new Object[] { args }); } catch (InvocationTargetException | IllegalArgumentException | IllegalAccessException | NoSuchMethodException | ClassNotFoundException | IOException e) { System.out.println("E4: " + e.getMessage()); return ERROR; } String cmd = "python /home/chanakya/NetBeansProjects/Concepto/src/java/generate/add_to_graph.py \"/home/chanakya/NetBeansProjects/Concepto/UploadedFiles/" + temp_filename + "_OllieOutput.txt\""; String[] finalCommand; finalCommand = new String[3]; finalCommand[0] = "/bin/sh"; finalCommand[1] = "-c"; finalCommand[2] = cmd; System.out.println("CMD: " + cmd); try { //ProcessBuilder builder = new ProcessBuilder(finalCommand); //builder.redirectErrorStream(true); //Process process = builder.start(); Process process = Runtime.getRuntime().exec(finalCommand); int exitVal = process.waitFor(); System.out.println("Process exitValue2: " + exitVal); } catch (Throwable t) { System.out.println("E5: " + t.getMessage()); return ERROR; } cmd = "python /home/chanakya/NetBeansProjects/Concepto/src/java/generate/json_correct.py"; finalCommand = new String[3]; finalCommand[0] = "/bin/sh"; finalCommand[1] = "-c"; finalCommand[2] = cmd; try { //Process process = Runtime.getRuntime().exec(finalCommand); ProcessBuilder builder = new ProcessBuilder(finalCommand); // builder.redirectErrorStream(true); Process process = builder.start(); int exitVal = process.waitFor(); System.out.println("Process exitValue3: " + exitVal); } catch (Throwable t) { System.out.println("E6: " + t.getMessage()); return ERROR; } try { List<String> temp_text_1 = FileUtils .readLines(FileUtils.getFile("/home/chanakya/NetBeansProjects/Concepto/web", "new_graph.json")); StringBuilder text_1 = new StringBuilder(); for (String s : temp_text_1) { text_1.append(s); } concept_map.setOutput_text(text_1.toString()); } catch (IOException e) { System.out.println("E7: " + e.getMessage()); return ERROR; } Random rand = new Random(); int unique_id = rand.nextInt(99999999); System.out.println("Going In DB"); try { MongoClient mongo = new MongoClient(); DB db = mongo.getDB("Major"); DBCollection collection = db.getCollection("ConceptMap"); BasicDBObject document = new BasicDBObject(); document.append("InputText", concept_map.getInput_text()); document.append("OutputText", concept_map.getOutput_text()); document.append("ChapterName", concept_map.getChapter_name()); document.append("ChapterNumber", concept_map.getChapter_number()); document.append("SectionName", concept_map.getSection_name()); document.append("SectionNumber", concept_map.getSection_number()); document.append("UniqueID", Integer.toString(unique_id)); collection.insert(document); //collection.save(document); } catch (MongoException e) { System.out.println("E8: " + e.getMessage()); return ERROR; } catch (UnknownHostException ex) { Logger.getLogger(MapGenerateAction.class.getName()).log(Level.SEVERE, null, ex); System.out.println("E9"); return ERROR; } System.out.println("Out DB"); return SUCCESS; }
From source file:generate.ShowArticlesAction.java
public String execute() throws ClassNotFoundException, SQLException, IOException { List<DBObject> documents = new ArrayList<>(); System.out.println("Mark 0"); try {/*from www . j a v a 2s .c om*/ MongoClient mongo = new MongoClient(); DB db = mongo.getDB("Major"); DBCollection collection = db.getCollection("ConceptMap"); DBCursor cursor = collection.find(); documents = cursor.toArray(); cursor.close(); } catch (MongoException e) { System.out.println("ERRRRRORRR: " + e.getMessage()); return ERROR; } catch (UnknownHostException ex) { Logger.getLogger(MapGenerateAction.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("Mark 1"); Map<String, ArrayList<String>> chap_to_section = new HashMap<>(); Map<String, String> id_to_section = new HashMap<>(); for (DBObject document : documents) { String c_name = document.get("ChapterName").toString(); boolean has_key = chap_to_section.containsKey(c_name); ArrayList<String> sections = new ArrayList<>(); sections.add(document.get("SectionName").toString()); if (has_key) { sections.addAll(chap_to_section.get(c_name)); chap_to_section.put(c_name, sections); } else { chap_to_section.put(c_name, sections); } id_to_section.put(document.get("SectionName").toString(), document.get("UniqueID").toString()); } FileWriter file = null; try { file = new FileWriter("/home/chanakya/NetBeansProjects/Concepto/web/Chapters_Sections.json"); } catch (IOException ex) { Logger.getLogger(ShowArticlesAction.class.getName()).log(Level.SEVERE, null, ex); } JSONArray jarr = new JSONArray(); for (String key : chap_to_section.keySet()) { JSONObject jobj = new JSONObject(); JSONArray arr = new JSONArray(); for (String val : chap_to_section.get(key)) { JSONObject temp = new JSONObject(); temp.put("name", val); temp.put("id", id_to_section.get(val).toString()); arr.add(temp); } jobj.put("sname", arr); jobj.put("cname", key); jarr.add(jobj); } System.out.println("Mark 2"); //JSONObject obj = new JSONObject(); //obj.put("cmap", jarr); file.write(jarr.toJSONString()); file.flush(); file.close(); System.out.println("Mark 3"); return SUCCESS; }
From source file:generate.ShowConceptMapAction.java
public String execute() throws ClassNotFoundException, SQLException, IOException { DBObject document = new BasicDBObject(); System.out.println("Uinque ID Value:" + getIdd()); try {/*w w w . j a v a2s . com*/ MongoClient mongo = new MongoClient(); DB db = mongo.getDB("Major"); DBCollection collection = db.getCollection("ConceptMap"); BasicDBObject query = new BasicDBObject(); query.put("UniqueID", getIdd()); document = collection.findOne(query); } catch (MongoException e) { System.out.println("ERRRRRORRR: " + e.getMessage()); return ERROR; } catch (UnknownHostException ex) { Logger.getLogger(MapGenerateAction.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("DB Output: " + document.get("OutputText").toString()); setData(document.get("OutputText").toString()); try { FileWriter file = new FileWriter("/home/chanakya/NetBeansProjects/Concepto/web/new_graph.json"); file.write(getData()); file.flush(); file.close(); } catch (IOException e) { return ERROR; //e.printStackTrace(); } return SUCCESS; }
From source file:gov.wa.wsdot.cms.templates.ProjectTemplate.java
License:Open Source License
@Override public ChannelsAndPostingsBase build(ChannelsAndPostingsBase item, HashMap<String, String> controlsMap, HashMap<String, String> genericPropertiesMap) { StringBuilder leftNav = new StringBuilder(); StringBuilder update = new StringBuilder(); StringBuilder pageContent = new StringBuilder(); StringBuilder contact = new StringBuilder(); StringBuilder map = new StringBuilder(); List<String> fundingList = new ArrayList<String>(); MongoClient mongo = null; try {//from ww w . j av a2 s .c om mongo = new MongoClient("localhost"); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } DB db = mongo.getDB("projects"); DBCollection projectsCollection = db.getCollection("posts"); BasicDBObject query = new BasicDBObject("Link", "/" + item.getLocation().replace(">>", "/") + "/"); DBCursor cursor = projectsCollection.find(query); try { while (cursor.hasNext()) { DBObject dbObject = cursor.next(); item.setProjectId(dbObject.get("ID").toString()); item.setCounties(dbObject.get("County").toString()); item.setRegions(dbObject.get("Region").toString()); item.setHighways(getHighwayTaxonomy(dbObject.get("Highway").toString())); if (!dbObject.get("Nickel").toString().equalsIgnoreCase("0")) { fundingList.add("Nickel"); } else if (!dbObject.get("Partner").toString().equalsIgnoreCase("0")) { fundingList.add("TPA"); } else if (!dbObject.get("FedStim").toString().equalsIgnoreCase("0")) { fundingList.add("ARRA"); } } String[] fundingArray = fundingList.toArray(new String[fundingList.size()]); item.setFunding(Arrays.toString(fundingArray).replace("[", "").replace("]", "").replace(",", ";")); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { cursor.close(); mongo.close(); } // This can be concatenated into the leftNav field leftNav.append(""); if (controlsMap.get("LeftNav") != null) { leftNav.append(controlsMap.get("LeftNav")); } if (controlsMap.get("LeftNavPlaceholderDefinition2") != null) { leftNav.append(controlsMap.get("LeftNavPlaceholderDefinition2")); } item.setLeftNav(leftNav.toString()); // All this can be concatenated into the projectUpdate field update.append("<p>"); update.append("<strong>" + controlsMap.get("ProjectUpdateDate") + "</strong>"); update.append("</p>"); update.append(controlsMap.get("ProjectUpdate")); item.setUpdate(update.toString()); // All this can be concatenated into the pageContent field if (controlsMap.get("OverviewDefinition") != null) { pageContent.append("<p>"); pageContent.append(controlsMap.get("OverviewDefinition")); pageContent.append("</p>"); } if (controlsMap.get("What") != null) { pageContent.append("<p>"); pageContent.append("<strong>Why is WSDOT " + controlsMap.get("What") + "</strong>"); pageContent.append("<br />"); pageContent.append(controlsMap.get("Why")); pageContent.append("</p>"); } if (controlsMap.get("EndResult") != null) { pageContent.append("<p>"); pageContent.append("<strong>The End Result</strong>"); pageContent.append("<br />"); pageContent.append(controlsMap.get("EndResult")); pageContent.append("</p>"); } if (controlsMap.get("ProjectBenefits") != null) { pageContent.append("<p>"); pageContent.append("<strong>Project Benefits</strong>"); pageContent.append("<br />"); pageContent.append(controlsMap.get("ProjectBenefits")); pageContent.append("</p>"); } if (controlsMap.get("ProjectTimelines") != null) { pageContent.append("<p>"); pageContent.append("<strong>What is the project timeline?</strong>"); pageContent.append("<br />"); pageContent.append(controlsMap.get("ProjectTimelines")); pageContent.append("</p>"); } if (controlsMap.get("Financial") != null) { pageContent.append("<p>"); pageContent.append("<strong>Financial Information</strong>"); pageContent.append("<br />"); pageContent.append(controlsMap.get("Financial")); pageContent.append("</p>"); } item.setPageContent(pageContent.toString()); // This will be separate and go into contact field if (controlsMap.get("Contact") != null) { contact.append("<p>"); contact.append("<strong>How can I get more information?<br />Contact:</strong><br />"); contact.append(controlsMap.get("Contact")); contact.append("</p>"); } item.setContact(contact.toString()); item.setPhase(getProjectPhaseTaxonomy(controlsMap.get("PhaseImage"))); // This can be concatenated into the projectMap field if (controlsMap.get("MapPlaceholder") != null) { map.append(controlsMap.get("MapPlaceholder")); } // FlickrLightbox <- Ignore for now // This appears under Map -> [Flickr Photos] -> RightPlaceHolder if (controlsMap.get("RightPlaceHolder") != null) { map.append(controlsMap.get("RightPlaceHolder")); } item.setLegacyMap(map.toString()); // Process GenericProperties item.setShowSignageDisclaimer(genericPropertiesMap.get("ShowCostEscalation")); item.setShowFinancialTable(genericPropertiesMap.get("ShowFinancialTable")); item.setShowMonthlyUpdateLeftNav(genericPropertiesMap.get("ShowMonthlyUpdateLeftNav")); item.setShowFlickrLightbox(genericPropertiesMap.get("ShowFlickrLightbox")); try { Pattern pattern = Pattern.compile("([\\d+]{10,})"); Matcher matcher = pattern.matcher(genericPropertiesMap.get("FlickrFeedURL")); if (matcher.find()) { item.setFlickrAlbumId(matcher.group(1)); } } catch (NullPointerException e) { } return item; }
From source file:govt_import_export.aircrafts2.java
public aircrafts2(String make_model_selected, String type_selected) { initComponents();/*w ww .ja v a 2 s . c o m*/ //System.out.println(make_model_selected+type_selected); type = type_selected; make_model = make_model_selected; try { MongoClient mongo = new MongoClient("localhost", 27017); DB aircrafts_info = mongo.getDB("AIRCRAFTSINFO"); DBCollection info = aircrafts_info.getCollection("INFO"); BasicDBObject search = new BasicDBObject(); search.put("Model", make_model); DBCursor cursor = info.find(search); while (cursor.hasNext()) zzz = cursor.next().toString(); zzz = zzz.substring(zzz.indexOf("st\" : \"") + 7); zzz = zzz.substring(0, zzz.indexOf("USD")); totalcost.setText(zzz); TF.setText(type); units_string = (String) JCB3.getSelectedItem(); java_month = (String) month.getSelectedItem(); java_year = (String) year.getSelectedItem(); unitsXcost = Long.parseLong(zzz) * Long.parseLong(units_string); unitsXcost_string = Long.toString(unitsXcost); DBCursor c = info.find(); DBObject display2; while (c.hasNext()) { display2 = c.next(); jLabel9.setText( "<html> Model: " + (display2.get("Model").toString()) + "<br> Country: " + (display2.get("Country").toString()) + "<br> Weight: " + (display2.get("Weight").toString()) + "<br> Range: " + (display2.get("Range").toString()) + "<br> Top speed: " + (display2.get("Top_speed").toString()) + "<br> Cost: " + (display2.get("Cost").toString()) + "<br> Passenger seats: " + (display2.get("Passenger_seats").toString()) + "</html>"); } } catch (UnknownHostException | MongoException e) { } }
From source file:govt_import_export.aircrafts2.java
private void placeorderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_placeorderActionPerformed try {//from www .j ava2s . c o m MongoClient mongo = new MongoClient("localhost", 27017); DB db0 = mongo.getDB("admindata"); DBCollection collection0 = db0.getCollection("admin"); DBCursor c = collection0.find(); DBObject o; while (c.hasNext()) { o = c.next(); if (o.get("rate") != null) { db_rate = o.get("rate").toString(); } } c = collection0.find(); while (c.hasNext()) { o = c.next(); if (o.get("balance") != null) { db_balance = nf.format(o.get("balance")); } } ratio = ((double) unitsXcost) / Double.parseDouble(db_balance); newbalance = Long.parseLong(db_balance) - unitsXcost; newrate = Double.parseDouble(db_rate) * pow(Math.E, ratio); System.out.println("'newrate'" + newrate); //System.out.println(newbalance); String q = nf.format(newbalance); //System.out.println(q); //--------------------setting the updated values in the db---------------------- BasicDBObject searchupdate = new BasicDBObject(); searchupdate.append("rate", Double.parseDouble(db_rate)); //finds the document(s) where "date":last_activity BasicDBObject update = new BasicDBObject(); update.append("$set", new BasicDBObject("rate", /*Double.toString(newrate)*/newrate)); collection0.update(searchupdate, update); //----- BasicDBObject searchupdate1 = new BasicDBObject(); searchupdate1.append("balance", Long.parseLong(db_balance)); BasicDBObject update1 = new BasicDBObject(); update1.append("$set", new BasicDBObject("balance", Long.parseLong(q))); collection0.update(searchupdate1, update1); //------------------------------------------------------------------------------ DB db = mongo.getDB("AIRCRAFTS"); DBCollection collection = db.getCollection(type); //insert BasicDBObject document = new BasicDBObject(); document.append("model", make_model); document.append("type", type); document.append("cost", zzz); document.append("month", java_month); document.append("year", java_year); document.append("units", Integer.parseInt(units_string)); document.append("totalcost", totalcost.getText()); javax.swing.JOptionPane.showMessageDialog(aircrafts2.this, "Waiting for acceptance"); collection.insert(document); } catch (UnknownHostException | MongoException e) { //e.printStackTrace(); } }
From source file:govt_import_export.Order.java
public autoexpo() { initComponents();/*from w w w . j a va 2 s . c o m*/ groupButton(); System.out.println("kkk"); try { MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("automobile_expo"); DBCollection col = db.getCollection("KTM"); BasicDBObject obj = new BasicDBObject(); obj.put("model_name", "RC390"); obj.put("date", "03-05-2013"); obj.put("EngineType", "Petrol"); obj.put("EngineDisplacement", "373cc"); obj.put("Maximum_torque", "35Nm@2000rpm"); obj.put("Noof_cylinders", 1); obj.put("Maximum_power", "43.5kw@8500rpm"); obj.put("Seating_Capacity", 2); obj.put("Length", "1375mm"); obj.put("Width", "600mm"); obj.put("Height", "1065mm"); obj.put("Cost", "205000INR"); //col.insert(obj); //BasicDBObject n=new BasicDBObject(); //n.append("model_name","i20"); //col.remove(n); } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } }