List of usage examples for com.mongodb BasicDBObject append
@Override public BasicDBObject append(final String key, final Object val)
From source file:com.softlyinspired.jlw.script.validationScript.java
License:Open Source License
/** * Write details of existing script to mongodb * @param scriptId//from w ww. ja v a2s . c o m * @param scriptText * @param scriptCategory * @param scriptTitle * @param scriptConnection * @throws UnknownHostException */ private void writeExistingScript(int scriptId, String scriptText, String scriptCategory, String scriptTitle, String scriptConnection) throws UnknownHostException { DBCollection coll = repoConnection.getScriptCollection(); BasicDBObject updateQuery = new BasicDBObject(); BasicDBObject searchQuery = new BasicDBObject().append("scriptId", scriptId); DBObject changes = new BasicDBObject().append("scriptText", scriptText) .append("ScriptCategory", scriptCategory).append("scriptTitle", scriptTitle) .append("scriptConnection", scriptConnection); updateQuery.append("$set", changes); try { coll.update(searchQuery, updateQuery); } catch (Exception e) { JLWUtilities.scriptErrorMessage("Error creating script"); } }
From source file:com.spring.tutorial.controllers.DefaultController.java
@RequestMapping(value = "/dropbox-auth-finished", method = RequestMethod.GET) public String authenticated(HttpServletResponse response, HttpServletRequest request, ModelMap map) throws DbxException, IOException { DbxAuthFinish authFinish;/*w w w . ja va 2 s . co m*/ String returnTo = "mydrive/mydrive"; final String APP_KEY = "mt6yctmupgrodlm"; final String APP_SECRET = "p68kiiyvdctftuv"; DbxAppInfo appInfo = new DbxAppInfo(APP_KEY, APP_SECRET); try { String redirectUrl = getUrl(request, "http://localhost:8080/FOU_1/dropbox-auth-finished"); // Select a spot in the session for DbxWebAuth to store the CSRF token. HttpSession session = request.getSession(); String sessionKey = "dropbox-auth-csrf-token"; DbxSessionStore csrfTokenStore = new DbxStandardSessionStore(session, sessionKey); auth = new DbxWebAuth(getRequestConfig(request), appInfo, redirectUrl, csrfTokenStore); authFinish = auth.finish(request.getParameterMap()); } catch (DbxWebAuth.BadRequestException ex) { log("On /dropbox-auth-finish: Bad request: " + ex.getMessage()); response.sendError(400); return returnTo; } catch (DbxWebAuth.BadStateException ex) { // Send them back to the start of the auth flow. response.sendRedirect("http://localhost:8080/FOU_1/dropbox-auth-finished" + ex.getMessage()); return returnTo; } catch (DbxWebAuth.CsrfException ex) { log("On /dropbox-auth-finish: CSRF mismatch: " + ex.getMessage()); return returnTo; } catch (DbxWebAuth.NotApprovedException ex) { return "redirect:my-drive/dropbox/home"; } catch (DbxWebAuth.ProviderException ex) { log("On /dropbox-auth-finish: Auth failed: " + ex.getMessage()); response.sendError(503, "Error communicating with Dropbox." + ex.getMessage()); return returnTo; } catch (DbxException ex) { log("On /dropbox-auth-finish: Error getting token: " + ex.getMessage()); response.sendError(503, "Error communicating with Dropbox." + ex.getMessage()); return returnTo; } String accessToken = authFinish.accessToken; DbxClient client = new DbxClient(config, accessToken); MongoClient mongoClient = new MongoClient(); DB db = mongoClient.getDB("fou"); char[] pass = "mongo".toCharArray(); boolean auth = db.authenticate("emime", pass); DBCollection collection = db.getCollection("users"); if (auth == true) { BasicDBObject newDocument = new BasicDBObject(); newDocument.append("$set", new BasicDBObject().append("dropbox_token", accessToken)); BasicDBObject searchQuery = new BasicDBObject().append("id", request.getSession().getAttribute("id")); collection.update(searchQuery, newDocument); } map.addAttribute("title", "my-drive"); request.getSession().setAttribute("dropbox_token", accessToken); response.sendRedirect("http://localhost:8080/FOU_1/my-drive/dropbox/home"); return "mydrive/dropbox"; }
From source file:com.spring.tutorial.controllers.DefaultController.java
@RequestMapping(value = "/my-drive/dropbox/edit", method = RequestMethod.POST) public @ResponseBody String editDropboxFile(HttpServletRequest request) throws IOException, DbxException, Exception { String tags = request.getParameter("tags"); String description = request.getParameter("description"); String path = request.getParameter("path"); MongoData mongoData = new MongoData(); DB db = mongoData.getDB();/* w ww . j a v a 2 s. c o m*/ DBCollection collection = db.getCollection(request.getSession().getAttribute("id") + "_dropbox_files_meta"); BasicDBObject document = new BasicDBObject(); document.append("tags", tags); document.append("description", description); BasicDBObject newDocument = new BasicDBObject(); newDocument.append("$set", document); BasicDBObject searchQuery = new BasicDBObject().append("path", path); collection.update(searchQuery, newDocument); return "success"; }
From source file:com.spring.tutorial.dropbox.DropBoxAuth.java
public void getDropboxPaths(String id, List<String> paths, String path) throws DbxException, UnknownHostException, Exception { DbxEntry.WithChildren listing = client.getMetadataWithChildren(path); for (DbxEntry child : listing.children) { if (child.isFolder()) { getDropboxPaths(id, paths, child.path); }//from w ww . ja va 2s . c om paths.add(child.path); } MongoData mongoData = new MongoData(); DB db = mongoData.getDB(); DBCollection collection = db.getCollection("users"); DBObject document = new BasicDBObject(); document.put("dropbox_hash", listing.hash); BasicDBObject newDocument = new BasicDBObject(); newDocument.append("$set", document); BasicDBObject searchQuery = new BasicDBObject().append("id", id); collection.update(searchQuery, newDocument); }
From source file:com.spring.tutorial.dropbox.DropBoxAuth.java
public void fetchFilesAndFolders(String id, DbxClient client, String path) throws DbxException, UnknownHostException, Exception { MongoData mongoData = new MongoData(); DB db = mongoData.getDB();//from www .jav a 2s . c o m DBCollection collection = db.getCollection(id + "_dropbox_files_meta"); DBCursor cursor = collection.find(); DbxEntry.WithChildren listing = client.getMetadataWithChildren(path); for (DbxEntry child : listing.children) { String fileInfo = child.toString(); DropboxEntity entity; if (child.isFile()) { String rev = fileInfo.substring(fileInfo.indexOf("rev=") + 5, fileInfo.indexOf(")") - 1); String fileSize = fileInfo.substring(fileInfo.indexOf("humanSize=") + 11, fileInfo.indexOf("\", lastModified")); String fileLastModified = fileInfo.substring(fileInfo.indexOf("lastModified=") + 14, fileInfo.indexOf("\", clientMtime")); entity = new DropboxEntity(child.name, "file", fileSize, fileLastModified, child.path, rev); DBObject document = new BasicDBObject(); document.put("rev", rev); document.put("fileSize", fileSize); document.put("lastModified", fileLastModified); document.put("name", child.name); document.put("path", child.path); document.put("type", "file"); cursor = collection.find(); boolean found = false; while (cursor.hasNext()) { DBObject doc = cursor.next(); String path1 = (String) doc.get("path"); if (path1.equals(child.path)) { found = true; } } if (found) { document.put("found", "true"); BasicDBObject newDocument = new BasicDBObject(); newDocument.append("$set", document); BasicDBObject searchQuery = new BasicDBObject().append("path", child.path); collection.update(searchQuery, newDocument); } else { document.put("tags", ""); document.put("description", ""); document.put("found", "false"); collection.insert(document); } } else { entity = new DropboxEntity(child.name, "folder", child.path); DBObject document = new BasicDBObject(); document.put("rev", ""); document.put("fileSize", ""); document.put("lastModified", ""); document.put("name", child.name); document.put("path", child.path); document.put("type", "folder"); cursor = collection.find(); boolean found = false; if (cursor.hasNext()) { while (cursor.hasNext()) { DBObject doc = cursor.next(); String path1 = (String) doc.get("path"); if (path1.equals(child.path)) { found = true; } } } if (found) { document.put("found", "true"); BasicDBObject newDocument = new BasicDBObject(); newDocument.append("$set", document); BasicDBObject searchQuery = new BasicDBObject().append("path", child.path); collection.update(searchQuery, newDocument); } else { document.put("tags", ""); document.put("description", ""); document.put("found", "false"); collection.insert(document); } fetchFilesAndFolders(id, client, child.path); } } }
From source file:com.spring.tutorial.entitites.FileUploader.java
public String upload() throws IOException, ServletException, FacebookException { OutputStream output = null;// ww w. java 2 s . com InputStream fileContent = null; final Part filePart; final File file; try { filePart = request.getPart("file"); fileContent = filePart.getInputStream(); MongoClient mongoClient = new MongoClient(); mongoClient = new MongoClient(); DB db = mongoClient.getDB("fou"); char[] pass = "mongo".toCharArray(); boolean auth = db.authenticate("admin", pass); file = File.createTempFile("fileToStore", "tmp"); file.deleteOnExit(); FileOutputStream fout = new FileOutputStream(file); int read = 0; byte[] bytes = new byte[1024]; while ((read = fileContent.read(bytes)) != -1) { fout.write(bytes, 0, read); } GridFS gridFS = new GridFS(db, request.getSession().getAttribute("id") + "_files"); GridFSInputFile gfsInputFile = gridFS.createFile(file); gfsInputFile.setFilename(filePart.getSubmittedFileName()); gfsInputFile.save(); DBCollection collection = db.getCollection(request.getSession().getAttribute("id") + "_files_meta"); BasicDBObject metaDocument = new BasicDBObject(); metaDocument.append("name", filePart.getSubmittedFileName()); metaDocument.append("size", filePart.getSize()); metaDocument.append("content-type", filePart.getContentType()); metaDocument.append("file-id", gfsInputFile.getId()); metaDocument.append("tags", request.getParameter("tags")); metaDocument.append("description", request.getParameter("description")); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); metaDocument.append("last_modified", dateFormat.format(new Date())); collection.insert(metaDocument); } catch (Exception e) { return "message:" + e.getMessage(); } finally { if (output != null) { output.close(); } if (fileContent != null) { fileContent.close(); } } return "success"; }
From source file:com.spring.tutorial.mongo.MongoDB.java
public boolean registerUser() { if (userExist()) { try {/*from www . ja va 2 s . com*/ BasicDBObject document = new BasicDBObject(); document.append("username", user.getUsername()); document.append("email", user.getEmail()); document.append("password", user.getPassword()); document.append("dropbox_token", user.getDropboxAccessToken()); document.append("dropbox_hash", ""); if (user.getId().equals("none")) { String id = Long.toString(System.currentTimeMillis()); document.append("id", id); user.setId(id); } else { document.append("id", user.getId()); } DBCollection collection = db.getCollection("users"); collection.insert(document); return true; } catch (Exception e) { return false; } } return true; }
From source file:com.sqm.dashboard.dao.impl.UserDaoImpl.java
License:Apache License
public boolean addUser(String firstname) throws UnknownHostException { // String passwordHash = makePasswordHash(password, // Integer.toString(random.nextInt())); BasicDBObject user = new BasicDBObject(); System.out.println("In USerDAO: " + firstname); user.append("firstname", firstname); try {//from w ww . j a va 2 s . com final DBCollection usersCollection; final MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost")); final DB blogDatabase = mongoClient.getDB("blog"); usersCollection = blogDatabase.getCollection("user"); usersCollection.insert(user); return true; } catch (MongoException.DuplicateKey e) { System.out.println("Username already in use: " + firstname); return false; } }
From source file:com.stratio.decision.functions.SaveToMongoActionExecutionFunction.java
License:Apache License
@Override public void process(Iterable<StratioStreamingMessage> messages) throws Exception { Integer partitionSize = maxBatchSize; if (partitionSize == null || partitionSize <= 0) { partitionSize = Iterables.size(messages); }//from w w w. ja v a2s. c o m Iterable<List<StratioStreamingMessage>> partitionIterables = Iterables.partition(messages, partitionSize); try { for (List<StratioStreamingMessage> messageList : partitionIterables) { Map<String, BulkWriteOperation> elementsToInsert = new HashMap<String, BulkWriteOperation>(); for (StratioStreamingMessage event : messageList) { BasicDBObject object = new BasicDBObject(TIMESTAMP_FIELD, event.getTimestamp()); for (ColumnNameTypeValue columnNameTypeValue : event.getColumns()) { object.append(columnNameTypeValue.getColumn(), columnNameTypeValue.getValue()); } BulkWriteOperation bulkInsertOperation = elementsToInsert.get(event.getStreamName()); if (bulkInsertOperation == null) { bulkInsertOperation = getDB().getCollection(event.getStreamName()) .initializeUnorderedBulkOperation(); elementsToInsert.put(event.getStreamName(), bulkInsertOperation); getDB().getCollection(event.getStreamName()) .createIndex(new BasicDBObject(TIMESTAMP_FIELD, -1)); } bulkInsertOperation.insert(object); } for (Entry<String, BulkWriteOperation> stratioStreamingMessage : elementsToInsert.entrySet()) { stratioStreamingMessage.getValue().execute(); } } } catch (Exception e) { log.error("Error saving in Mongo: " + e.getMessage()); } }
From source file:com.stratio.qa.utils.MongoDBUtils.java
License:Apache License
/** * Create a MongoDB collection./* w w w . j av a 2s . c om*/ * * @param colectionName * @param options */ public void createMongoDBCollection(String colectionName, DataTable options) { BasicDBObject aux = new BasicDBObject(); // Recorremos las options para castearlas y aadirlas a la collection List<List<String>> rowsOp = options.raw(); for (int i = 0; i < rowsOp.size(); i++) { List<String> rowOp = rowsOp.get(i); if (rowOp.get(0).equals("size") || rowOp.get(0).equals("max")) { int intproperty = Integer.parseInt(rowOp.get(1)); aux.append(rowOp.get(0), intproperty); } else { Boolean boolProperty = Boolean.parseBoolean(rowOp.get(1)); aux.append(rowOp.get(0), boolProperty); } } dataBase.createCollection(colectionName, aux); }