List of usage examples for com.mongodb DBCollection insert
public WriteResult insert(final List<? extends DBObject> documents)
From source file:com.ayu.filter.RegularService.java
License:Open Source License
@Async public void registerUser(String ip, String date, String type, String document) { //System.out.println(" Attack from "+ip +" captured at"+ date+" "+"type of attack is"+" "+type); //System.out.println(" Database Insertion "); try {/*w w w . j a v a2 s . c o m*/ Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } MongoClient mongoClient = null; try { mongoClient = new MongoClient(); } catch (UnknownHostException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // or, to connect to a replica set, supply a seed list of members //MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress("localhost", 27017), // new ServerAddress("localhost", 27018), // new ServerAddress("localhost", 27019))); DB db = mongoClient.getDB(document); DBCollection coll; coll = db.getCollection(document); BasicDBObject doc = new BasicDBObject("Ip-Address", ip).append("Date", date).append("Attack-Type", type); //System.out.println("Data Display"); coll.insert(doc); mongoClient.close(); //System.out.println(" Asynchronous method call of database Complete "); }
From source file:com.badger.observationmongotest.execute.Main.java
public static void main(String[] args) throws ParseException, UnknownHostException, IOException { List<Observation> observations = new LinkedList(); Customer customer = new Customer(); customer.setName("Mr Customer"); customer.setId("cid123"); customer.setBackOfficeId("boid123"); SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd"); String dateStr = "2015/08/10"; Date date = format.parse(dateStr); CustomerObservationReport report = new CustomerObservationReport(customer); MonthlyProductOrderCountIssue productOrderCountIssue = new MonthlyProductOrderCountIssue(); productOrderCountIssue.setActionRequired(true); productOrderCountIssue.setCatagory("product issue"); productOrderCountIssue.setCurrentYear(2015); productOrderCountIssue.setCurrentYearValue(30); productOrderCountIssue.setCustomerId(customer.getId()); productOrderCountIssue.setDate(date); productOrderCountIssue.setDrop(50.0); productOrderCountIssue.setLastYearValue(60); productOrderCountIssue.setMonth("Feb"); productOrderCountIssue.setObservationId("oid123"); productOrderCountIssue.setPreviousYear(2014); productOrderCountIssue.setProductName("cool product"); productOrderCountIssue.setScore(4500); productOrderCountIssue.setType("monthy order count"); MonthlyProductOrderCountIssue monthlyProductOrderCountIssue = new MonthlyProductOrderCountIssue(); monthlyProductOrderCountIssue.setActionRequired(true); monthlyProductOrderCountIssue.setCatagory("product issue"); monthlyProductOrderCountIssue.setCurrentYear(2015); monthlyProductOrderCountIssue.setCurrentYearValue(30); monthlyProductOrderCountIssue.setCustomerId(customer.getId()); monthlyProductOrderCountIssue.setDate(date); monthlyProductOrderCountIssue.setDrop(50.0); monthlyProductOrderCountIssue.setLastYearValue(60); monthlyProductOrderCountIssue.setMonth("March"); monthlyProductOrderCountIssue.setObservationId("oid456"); monthlyProductOrderCountIssue.setPreviousYear(2014); monthlyProductOrderCountIssue.setProductName("cool product"); monthlyProductOrderCountIssue.setScore(4500); monthlyProductOrderCountIssue.setType("monthy order count"); MonthlyProductRevenueIssue monthlyProductRevenueIssue = new MonthlyProductRevenueIssue(); monthlyProductRevenueIssue.setActionRequired(true); monthlyProductRevenueIssue.setCatagory("product issue"); monthlyProductRevenueIssue.setCurrentYear(2015); monthlyProductRevenueIssue.setCurrentYearValue(3000.00); monthlyProductRevenueIssue.setCustomerId(customer.getId()); monthlyProductRevenueIssue.setDate(date); monthlyProductRevenueIssue.setDrop(50.0); monthlyProductRevenueIssue.setLastYearValue(6000.00); monthlyProductRevenueIssue.setMonth("Dec"); monthlyProductRevenueIssue.setObservationId("oid3445"); monthlyProductRevenueIssue.setPreviousYear(2014); monthlyProductRevenueIssue.setProductName("test product"); monthlyProductRevenueIssue.setScore(5667); monthlyProductRevenueIssue.setType("monthly product ervenue"); MonthlyRevenueIssue monthlyRevenueIssue = new MonthlyRevenueIssue(); monthlyRevenueIssue.setActionRequired(true); monthlyRevenueIssue.setCatagory("Reveue Issue"); monthlyRevenueIssue.setCurrentValue(3000); monthlyRevenueIssue.setCurrentYear(2015); monthlyRevenueIssue.setCustomerId(customer.getId()); monthlyRevenueIssue.setDate(date);// w w w .jav a 2 s .co m monthlyRevenueIssue.setDrop(45.0); monthlyRevenueIssue.setMonth("Nov"); monthlyRevenueIssue.setObservationId("oid4646646"); monthlyRevenueIssue.setPreviousValue(5000); monthlyRevenueIssue.setPreviousYear(2014); monthlyRevenueIssue.setScore(5600); monthlyRevenueIssue.setType("monthly revenue issue"); observations.add(monthlyRevenueIssue); observations.add(monthlyProductRevenueIssue); observations.add(monthlyProductOrderCountIssue); observations.add(productOrderCountIssue); report.setAccountId("acid123"); report.addObservations(observations); // BasicDBObject documentDetail = new BasicDBObject(); /** * documentDetail.put("accountId", report.getAccountId()); * documentDetail.put("customerId", report.getCustomerId()); * documentDetail.put("Observations", * report.getObservations().toString()); * */ MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("ObservationReports"); DBCollection col = db.getCollection("reports"); Gson gson = new Gson(); String json = gson.toJson(report); DBObject dbObject = (DBObject) JSON.parse(json); col.insert(dbObject); //DBObject query = BasicDBObjectBuilder.start().add("_id", report.getId()).get(); DBCursor cursor = col.find(); while (cursor.hasNext()) { System.out.println("First Cursor: " + cursor.next().get("observations")); } while (cursor.hasNext()) { DBObject dbobj = cursor.next(); Map map = dbObject.toMap(); CustomerObservationReport report2 = new CustomerObservationReport(customer); //System.out.println("observations " +dbObject.get("observations")); List<Observation> dbObservations = (List<Observation>) dbObject.get("observations"); report2.setAccountId(report.getAccountId()); report2.setCustomerId(report.getCustomerName()); report2.setBackOfficeId(report.getBackOfficeId()); report2.setObservations((dbObservations)); System.out.println(report2.getClass().getTypeName()); } }
From source file:com.bbc.remarc.util.ResourceManager.java
License:Apache License
private static void createDocumentsFromFileMap(HashMap<String, List<File>> fileMap, HashMap<String, ResourceType> typeMap, File properties, String resourcesDir) { DB db = MongoClient.getDB();/* w ww.jav a2s. com*/ Properties documentProps = processPropertiesFile(properties); if (documentProps == null) { log.error("could not create properties file. Abort directory."); return; } String theme = documentProps.getProperty("theme"); String decade = documentProps.getProperty("decade"); if (theme == null && decade == null) { log.error("ERROR! Properties file contained neither THEME nor DECADE. Abort directory."); return; } // now we process each key (document) in the hashmap, copying the // resources (file array) into the correct folder Set<String> keys = fileMap.keySet(); for (String key : keys) { log.debug("processing [" + key + "]"); // create document with id, theme and decade BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start(); documentBuilder.add("id", key); documentBuilder.add("theme", theme); documentBuilder.add("decade", decade); // based upon the documentType, we can determine all our urls and // storage variables ResourceType documentType = typeMap.get(key); File fileDestDirectory = null; // Get the relative base URL from an Environment variable if it has been set String relativefileBaseUrl = System.getenv(Configuration.ENV_BASE_URL); if (relativefileBaseUrl == null || "".equals(relativefileBaseUrl)) { relativefileBaseUrl = Configuration.DEFAULT_RELATIVE_BASE_URL; } else { relativefileBaseUrl += Configuration.CONTENT_DIR; } String mongoCollection = ""; switch (documentType) { case IMAGE: mongoCollection = "images"; fileDestDirectory = new File(resourcesDir + Configuration.IMAGE_DIR_NAME); relativefileBaseUrl += Configuration.IMAGE_DIR; break; case AUDIO: mongoCollection = "audio"; fileDestDirectory = new File(resourcesDir + Configuration.AUDIO_DIR_NAME); relativefileBaseUrl += Configuration.AUDIO_DIR; break; case VIDEO: mongoCollection = "video"; fileDestDirectory = new File(resourcesDir + Configuration.VIDEO_DIR_NAME); relativefileBaseUrl += Configuration.VIDEO_DIR; break; default: break; } List<File> files = fileMap.get(key); for (File resource : files) { log.debug("--- processing [" + resource.getName() + "]"); String resourceLocation = relativefileBaseUrl + resource.getName(); String extension = FilenameUtils.getExtension(resource.getName()); ResourceType fileType = getTypeFromExtension(extension); // now determine the value to store the resource under in MongoDB, different if an image or metadata String urlKey; switch (fileType) { case IMAGE: urlKey = "imageUrl"; break; case INFORMATION: urlKey = "metadata"; break; default: urlKey = (extension + "ContentUrl"); break; } // If the file is a metadata file, we want to read from it, otherwise we just add the location to the db if (fileType == ResourceType.INFORMATION) { String metadata = processMetadata(resource.getPath()); documentBuilder.add(urlKey, metadata); } else { documentBuilder.add(urlKey, resourceLocation); } } // insert the document into the database try { DBObject obj = documentBuilder.get(); log.debug("writing document to collection (" + mongoCollection + "): " + obj); db.requestStart(); DBCollection collection = db.getCollection(mongoCollection); collection.insert(documentBuilder.get()); } finally { db.requestDone(); } // write all the resource files to the correct directory log.debug("copying resources into " + fileDestDirectory.getPath()); for (File resource : files) { // We don't want to copy the metadata into the directory, so remove it here String extension = FilenameUtils.getExtension(resource.getName()); ResourceType fileType = getTypeFromExtension(extension); if (fileType != ResourceType.INFORMATION) { try { FileUtils.copyFileToDirectory(resource, fileDestDirectory); } catch (IOException e) { log.error("ERROR! Couldn't copy resource to directory: " + e); } } } } }
From source file:com.buzz.buzzdata.MongoBuzz.java
@Override public void Insert(String userid, String header, String content, Double lat, Double lng, String tags, String[] files) {//from ww w. j ava 2 s . c o m BasicDBObject document = new BasicDBObject(); document.put("userid", userid); document.put("header", header); document.put("content", content); document.put("tags", tags.split(",")); document.put("created", (new Date())); document.put("modified", (new Date())); BasicDBObject lng_obj = new BasicDBObject(); lng_obj.put("lng", lng); BasicDBObject lat_obj = new BasicDBObject(); lat_obj.put("lat", lat); document.put("loc", (new Double[] { lng, lat })); document.put("FilesCount", files.length); DBCollection coll = mongoDB.getCollection("BuzzInfo"); coll.insert(document); ObjectId buzz_id = (ObjectId) document.get("_id"); int i = 0; for (String file : files) { try { GridFS gridFS = new GridFS(mongoDB); InputStream file_stream = getFTPInputStream(file); String caption_filename = FilenameUtils.removeExtension(file) + "_caption.txt"; InputStream caption_stream = getFTPInputStream(caption_filename); StringWriter writer = new StringWriter(); Charset par = null; IOUtils.copy(caption_stream, writer, par); String caption = writer.toString(); GridFSInputFile in = gridFS.createFile(file_stream); in.setFilename(file); in.put("BuzzID", buzz_id); in.put("Caption", caption); in.put("PicNum", i); in.save(); } catch (IOException ex) { Logger.getLogger(MongoBuzz.class.getName()).log(Level.SEVERE, null, ex); } i++; } }
From source file:com.caci.dummyserver.MongoRepository.java
/** * Insert a new object into the specified collection. * @param table The name of the Mongo collection to insert into. * @param keys The list of key/value pairs. These are the path parameters. * @param json The json for the document to insert. * @return Returns the DAVE ID of the object. *//*from www. j a v a 2 s .c om*/ public String insertObject(String table, Collection<Pair<String, String>> keys, String json) throws Exception { DB db = mongo.getDB("Objects"); DBCollection col = db.getCollection(table); String daveId = generateDAVEID(); while (getObject(table, daveId, null) != null) { daveId = generateDAVEID(); } DBObject data = (DBObject) JSON.parse(json); data.put("id", daveId); json = data.toString(); if (keys == null) { keys = new ArrayList<>(); } keys.add(new Pair<>(":" + table, daveId)); DBObject obj = makeDBObject(keys, json); col.insert(obj); return daveId; }
From source file:com.callidusrobotics.droptables.model.DocumentDao.java
License:Open Source License
/** * Upserts a document into a collection. Creates the collection if it does not * exist. Creates the document if it does not exist. * * @param collectionName// ww w .j a va2 s.c o m * The collection to upsert to * @param document * The document to upsert * @return ObjectId of the upserted document */ public ObjectId upsertDocument(String collectionName, DBObject document) { DBCollection collection = getCollection(collectionName); collection.insert(document); return (ObjectId) document.get(DOC_ID); }
From source file:com.chdi.kundenverwaltung.KundenVerwaltungsLogic.java
public void insertCustomer(Customer customer) { DBCollection table = db.getCollection("user"); BasicDBObject query = new BasicDBObject(); query.append("ID", customer.getID()); query.append("CompanyName", customer.getCompanyName()); query.append("Name", customer.getName()); query.append("Adress", customer.getAdress()); table.insert(query); }
From source file:com.continuent.tungsten.replicator.applier.MongoApplier.java
License:Open Source License
/** * Applies row updates to MongoDB. Statements are discarded. {@inheritDoc} * /*from w ww . j ava 2 s .c om*/ * @see com.continuent.tungsten.replicator.applier.RawApplier#apply(com.continuent.tungsten.replicator.event.DBMSEvent, * com.continuent.tungsten.replicator.event.ReplDBMSHeader, boolean, * boolean) */ @Override public void apply(DBMSEvent event, ReplDBMSHeader header, boolean doCommit, boolean doRollback) throws ReplicatorException, ConsistencyException, InterruptedException { ArrayList<DBMSData> dbmsDataValues = event.getData(); // Iterate through values inferring the database name. for (DBMSData dbmsData : dbmsDataValues) { if (dbmsData instanceof StatementData) { if (logger.isDebugEnabled()) logger.debug("Ignoring statement"); } else if (dbmsData instanceof RowChangeData) { RowChangeData rd = (RowChangeData) dbmsData; for (OneRowChange orc : rd.getRowChanges()) { // Get the action as well as the schema & table name. ActionType action = orc.getAction(); String schema = orc.getSchemaName(); String table = orc.getTableName(); if (logger.isDebugEnabled()) { logger.debug("Processing row update: action=" + action + " schema=" + schema + " table=" + table); } // Process the action. if (action.equals(ActionType.INSERT)) { // Connect to the schema and collection. DB db = m.getDB(schema); DBCollection coll = db.getCollection(table); // Fetch column names. List<ColumnSpec> colSpecs = orc.getColumnSpec(); // Make a document and insert for each row. Iterator<ArrayList<ColumnVal>> colValues = orc.getColumnValues().iterator(); while (colValues.hasNext()) { BasicDBObject doc = new BasicDBObject(); ArrayList<ColumnVal> row = colValues.next(); for (int i = 0; i < row.size(); i++) { Object value = row.get(i).getValue(); setValue(doc, colSpecs.get(i), value); } if (logger.isDebugEnabled()) logger.debug("Adding document: doc=" + doc.toString()); coll.insert(doc); } } else if (action.equals(ActionType.UPDATE)) { // Connect to the schema and collection. DB db = m.getDB(schema); DBCollection coll = db.getCollection(table); // Ensure required indexes are present. ensureIndexes(coll, orc); // Fetch key and column names. List<ColumnSpec> keySpecs = orc.getKeySpec(); List<ColumnSpec> colSpecs = orc.getColumnSpec(); ArrayList<ArrayList<OneRowChange.ColumnVal>> keyValues = orc.getKeyValues(); ArrayList<ArrayList<OneRowChange.ColumnVal>> columnValues = orc.getColumnValues(); // Iterate across the rows. for (int row = 0; row < columnValues.size() || row < keyValues.size(); row++) { List<ColumnVal> keyValuesOfRow = keyValues.get(row); List<ColumnVal> colValuesOfRow = columnValues.get(row); // Prepare key values query to search for rows. DBObject query = new BasicDBObject(); for (int i = 0; i < keyValuesOfRow.size(); i++) { setValue(query, keySpecs.get(i), keyValuesOfRow.get(i).getValue()); } BasicDBObject doc = new BasicDBObject(); for (int i = 0; i < colValuesOfRow.size(); i++) { setValue(doc, colSpecs.get(i), colValuesOfRow.get(i).getValue()); } if (logger.isDebugEnabled()) { logger.debug("Updating document: query=" + query + " doc=" + doc); } DBObject updatedRow = coll.findAndModify(query, doc); if (logger.isDebugEnabled()) { if (updatedRow == null) logger.debug("Unable to find document for update: query=" + query); else logger.debug("Documented updated: doc=" + doc); } } } else if (action.equals(ActionType.DELETE)) { // Connect to the schema and collection. DB db = m.getDB(schema); DBCollection coll = db.getCollection(table); // Ensure required indexes are present. ensureIndexes(coll, orc); List<ColumnSpec> keySpecs = orc.getKeySpec(); ArrayList<ArrayList<OneRowChange.ColumnVal>> keyValues = orc.getKeyValues(); ArrayList<ArrayList<OneRowChange.ColumnVal>> columnValues = orc.getColumnValues(); // Iterate across the rows. for (int row = 0; row < columnValues.size() || row < keyValues.size(); row++) { List<ColumnVal> keyValuesOfRow = keyValues.get(row); // Prepare key values query to search for rows. DBObject query = new BasicDBObject(); for (int i = 0; i < keyValuesOfRow.size(); i++) { setValue(query, keySpecs.get(i), keyValuesOfRow.get(i).getValue()); } if (logger.isDebugEnabled()) { logger.debug("Deleting document: query=" + query); } DBObject deletedRow = coll.findAndRemove(query); if (logger.isDebugEnabled()) { if (deletedRow == null) logger.debug("Unable to find document for delete"); else logger.debug("Documented deleted: doc=" + deletedRow); } } } else { logger.warn("Unrecognized action type: " + action); return; } } } else if (dbmsData instanceof LoadDataFileFragment) { if (logger.isDebugEnabled()) logger.debug("Ignoring load data file fragment"); } else if (dbmsData instanceof RowIdData) { if (logger.isDebugEnabled()) logger.debug("Ignoring row ID data"); } else { logger.warn("Unsupported DbmsData class: " + dbmsData.getClass().getName()); } } // Mark the current header and commit position if requested. this.latestHeader = header; if (doCommit) commit(); }
From source file:com.data.DAO.MetodoPagoDAO.java
public static String crearRecibo(Integer idMetodoPago, String descripcion, Integer cuotas, float precio, Integer idReserva) {//from w w w . j a v a 2s. c o m String reciboCreado = null; try { // To connect to mongo dbserver MongoClient mongoClient = new MongoClient("localhost", 27017); // Now connect to your databases DB db = mongoClient.getDB("hoex"); System.out.println("Connect to database successfully"); DBCollection coll = db.getCollection("Metodo_pago"); System.out.println("Collection Metodo_pago selected successfully"); BasicDBObject doc = new BasicDBObject("idMetodoPago", idMetodoPago).append("descripcion", descripcion) .append("cuotas", cuotas).append("precio", precio).append("idReserva", idReserva); coll.insert(doc); System.out.println("Document inserted successfully"); reciboCreado = "Success"; } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } if (reciboCreado != null) { return "El recibo fue creado satisfactoriamente!"; } else { return "El recibo no ha sido creado!"; } }
From source file:com.davidsalter.cappedcollection.JavaDriverCappedCollection.java
License:Apache License
/** * @param args the command line arguments *//*from ww w . jav a2s . co m*/ public static void main(String[] args) throws UnknownHostException { MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost")); DB db = mongoClient.getDB("test"); DBCollection collection; if (!db.collectionExists("cappedLogsJavaDriver")) { BasicDBObject options = new BasicDBObject("capped", true); options.append("size", 4096); options.append("max", 5); collection = db.createCollection("cappedLogsJavaDriver", options); } else { collection = db.getCollection("cappedLogsJavaDriver"); } for (int i = 0; i < 8; i++) { BasicDBObject logEntry = new BasicDBObject("logId", i); collection.insert(logEntry); } }