Example usage for com.mongodb DBCollection find

List of usage examples for com.mongodb DBCollection find

Introduction

In this page you can find the example usage for com.mongodb DBCollection find.

Prototype

public DBCursor find(final DBObject query) 

Source Link

Document

Select documents in collection and get a cursor to the selected documents.

Usage

From source file:com.sanaldiyar.projects.nanohttpd.mongodbbasedsessionhandler.MongoDBBasedSessionHandler.java

/**
 * Request parser for session. Gets and builds session information
 *
 * @param request the request//  w w  w  .  j  av a  2s  . c o m
 * @return session manager
 */
@Override
public NanoSessionManager parseRequest(Request request) {
    MongoDBBasedSessionManager nanoSessionManager = null;
    DBObject session = null;
    String sessionid = null;
    for (Cookie cookie : request.getCookies()) {
        if (cookie.getName().equals(SESSIONCOOKIEID)) {
            sessionid = cookie.getValue();
            break;
        }
    }
    DBCollection sessions = managers.getCollection("sessions");
    if (sessionid != null) {
        DBCursor cursor = sessions.find(new BasicDBObject("sessionid", sessionid));
        List<DBObject> result = cursor.toArray();
        cursor.close();
        if (result.size() == 1) {
            session = result.get(0);
        }
        if (session != null) {
            if (((Date) session.get("expires")).getTime() <= new Date().getTime()) {
                sessions.remove(new BasicDBObject().append("sessionid", sessionid));
                session = null;
            }
        }
    }
    if (session == null) {
        do {
            sessionid = new BigInteger(128, srng).toString(32);
        } while (sessions.findOne(new BasicDBObject().append("sessionid", sessionid)) != null
                && !sessionid.equals("0"));
        session = new BasicDBObject();
        nanoSessionManager = new MongoDBBasedSessionManager(session);
        nanoSessionManager.setSessionID(sessionid);
        sessions.insert(session);
    } else {
        nanoSessionManager = new MongoDBBasedSessionManager(session);
    }
    return nanoSessionManager;
}

From source file:com.se452group4.db.InsertDriver.java

public static void main(String[] args) throws UnknownHostException {
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    DB db = mongoClient.getDB("Shop");
    DBCollection clothCollection = db.getCollection("Clothes");
    BasicDBObject cloth1 = new BasicDBObject();
    cloth1.put("clothesId", 1000);
    cloth1.put("type", "Dress");
    cloth1.put("brandName", "Zara");
    cloth1.put("price", 100);
    cloth1.put("gender", "Women");
    cloth1.put("quantity", 5);
    clothCollection.insert(cloth1);//from w w w .  ja  v a  2s  . com

    DBCursor clothCursor = clothCollection.find(cloth1);
    while (clothCursor.hasNext()) {
        System.out.println(clothCursor.next());
    }
}

From source file:com.servlet.ChangePassword.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from  www  .jav  a 2 s.com*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        String oldPass = request.getParameter("oldPass");
        String newPass = request.getParameter("newPass");
        String userEmail = request.getParameter("userEmail");

        DBcon dbcon = new DBcon();
        dbcon.getDbCon();
        DBCollection coll = dbcon.getData("employee");

        BasicDBObject search = new BasicDBObject("email", userEmail);

        DBCursor cursor = coll.find(search);
        DBObject dbo = cursor.next();
        Employee c = Employee.fromDBObject(dbo);
        PrintWriter out = response.getWriter();
        if (PasswordHash.validatePassword(oldPass, c.getPassword())) {

            BasicDBObject update = new BasicDBObject("$set",
                    new BasicDBObject("password", PasswordHash.createHash(newPass)));
            dbcon.updateData("employee", search, update);
            out.print("done");

        } else {

            // out.print("Your Old Password is Incorrect");
        }
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(ChangePassword.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeySpecException ex) {
        Logger.getLogger(ChangePassword.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.servlet.ClaimDetails.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/* w  w  w . j a  v a  2s. c o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String claimId = request.getParameter("claimid");
    PrintWriter out = response.getWriter();
    DBcon dbcon = new DBcon();
    dbcon.getDbCon();

    BasicDBObject search = new BasicDBObject("claimid", Integer.parseInt(claimId));
    DBCollection coll = dbcon.getData("claims");

    DBCursor cursor = coll.find(search);
    DBObject obj = cursor.next();
    JSONObject json = new JSONObject();

    Claims claims = Claims.fromDBObject2(obj);

    json.put("claimid", claims.getClaimId());
    json.put("date", claims.getDate());
    json.put("status", claims.getStatus());
    json.put("amount", claims.getTotal());
    json.put("empid", claims.getEmpId());
    json.put("details", claims.getDetails());

    out.print(json);

}

From source file:com.servlet.DeleteClaims.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from w  w  w .jav a2  s . c o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String idstr = request.getParameter("id"); // ID which is going to delete
    String claimstr = request.getParameter("claimid");// claim id
    String amountstr = request.getParameter("amount");// claim id

    DBcon dbcon = new DBcon();
    dbcon.getDbCon();
    int oid = Integer.parseInt(idstr);//parse string values to integer
    int claimId = Integer.parseInt(claimstr);
    double amount = Double.parseDouble(amountstr);

    BasicDBObject match = new BasicDBObject("docid", oid);//match the document id
    BasicDBObject push = new BasicDBObject("$pull", new BasicDBObject("details", match));
    BasicDBObject search = new BasicDBObject("claimid", claimId);// searched claim document

    dbcon.updateData("claims", search, push);

    DBCollection coll = dbcon.getData("claims");
    DBCursor cursor = coll.find(search);
    DBObject findObject = cursor.next();
    Claims mainClaimObject = Claims.fromDBObject2(findObject);//create a main claim object

    double total = mainClaimObject.getTotal();
    total -= amount;
    mainClaimObject.setTotal(total);//update the total claim amount
    DBObject mainObject = mainClaimObject.toDBObject2();//create DBObject 
    dbcon.updateData("claims", search, mainObject);//update the main claim

    //PrintWriter out = response.getWriter();
    //out.print(idstr + claimstr);
}

From source file:com.servlet.EditPendingClaims.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from   ww  w.  j a  va 2  s. c  om
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    int claimId = Integer.parseInt(request.getParameter("id"));

    DBcon dbcon = new DBcon();
    dbcon.getDbCon();

    BasicDBObject search = new BasicDBObject("claimid", claimId);
    DBCollection coll = dbcon.getData("claims");
    DBCursor cursor = coll.find(search);
    DBObject object = cursor.next();
    Claims claims = Claims.fromDBObject2(object);

    HttpSession session = request.getSession(true);
    session.setAttribute("c", claims); // create session for claims

}

From source file:com.servlet.EmployeeDetails.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from   w  ww  .  j  ava2  s. c o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String empid = request.getParameter("empid");

    DBcon dbcon = new DBcon();
    dbcon.getDbCon();

    BasicDBObject search = new BasicDBObject("empid", Integer.parseInt(empid));

    DBCollection coll = dbcon.getData("employee");

    DBCursor cursor = coll.find(search);
    DBObject obj = cursor.next();

    Employee emp = Employee.fromDBObject(obj);
    //JSONObject json = emp.toJson(emp);

    PrintWriter out = response.getWriter();

    //  out.print(json);

    //processRequest(request, response);
}

From source file:com.servlet.IndividualExpense.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/* www  . j a  v  a  2 s.co m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    DBcon dbcon = new DBcon();
    dbcon.getDbCon();
    JSONObject json = new JSONObject();
    DBCollection coll = dbcon.getData("claims");

    String searchid = request.getParameter("searchId");
    int empid = Integer.parseInt(searchid);
    BasicDBObject search = new BasicDBObject();
    search.append("status", "Approved");
    search.append("empid", empid);

    DBCursor cursor = coll.find(search);
    int foodSum = 0;
    int internetSum = 0;
    int otherSum = 0;
    while (cursor.hasNext()) {
        DBObject obj = cursor.next();
        ArrayList li = (ArrayList) obj.get("details");

        if (!li.isEmpty()) {

            Iterator<BasicDBObject> intI = li.iterator();
            while (intI.hasNext()) {
                BasicDBObject o = intI.next();
                Claims cl = Claims.fromDBObject(o);
                String billType = (String) cl.getBillType();
                if (billType.equals("Food")) {
                    foodSum += (int) cl.getAmount();

                } else if (billType.equals("Internet")) {
                    internetSum += (int) cl.getAmount();
                } else {
                    otherSum += (int) cl.getAmount();
                }

            }

        }
    }
    json.put("foodsum", foodSum);
    json.put("internetsum", internetSum);
    json.put("othersum", otherSum);
    out.print(json);
}

From source file:com.servlet.MonthlyClaimLimit.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from ww w. jav  a  2 s . c o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    try {
        //int claimId = Integer.parseInt(request.getParameter("claimid"));// both empid and claimid are integers
        String email = request.getParameter("email");

        DBcon dbcon = new DBcon();
        dbcon.getDbCon();// setup the database connection
        DBCollection coll = dbcon.getData("claims");

        Date currentDate = new Date();//current date
        DateFormat formatter = new SimpleDateFormat("MM/yyyy");

        currentDate = formatter.parse(formatter.format(currentDate));
        Date start = currentDate;
        Calendar c = Calendar.getInstance();
        c.setTime(currentDate);
        c.add(Calendar.MONTH, 1);
        Date end = c.getTime();

        BasicDBObject searchMonthExpence = new BasicDBObject();
        searchMonthExpence.append("status", "Approved");
        searchMonthExpence.append("email", email);
        searchMonthExpence.append("date", new BasicDBObject("$gte", start).append("$lt", end)); //send notifications

        DBCursor Limitcursor = coll.find(searchMonthExpence);
        double currentMonthTotal = 0;

        while (Limitcursor.hasNext()) {
            DBObject dBObject = Limitcursor.next();
            Claims claims = Claims.fromDBObject2(dBObject);
            currentMonthTotal += claims.getTotal();

        }

        out.print(currentMonthTotal);
    } catch (ParseException ex) {
        Logger.getLogger(MonthlyClaimLimit.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.servlet.UpdateClaim.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from   w  ww.  ja  va2s  .  co  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    double total = 0;
    //variable declaration
    FileItem item = null;
    String fieldName = "";
    String fieldValue = "";
    String fileName = "";
    boolean isImageExist = false;
    //current sessions
    Employee emp = (Employee) request.getSession().getAttribute("user");
    Claims cla = (Claims) request.getSession().getAttribute("c");

    //bean object
    Claims claims = new Claims();

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {

            List items = upload.parseRequest(request);
            Iterator iterator = items.iterator();

            while (iterator.hasNext()) {
                item = (FileItem) iterator.next();
                if (!item.isFormField()) { // check for regular form field 
                    fileName = item.getName();
                    if (!fileName.equals("")) {

                        String root = getServletContext().getRealPath("/");
                        response.getWriter().write(root);
                        File path = new File(root + "/images/uploads" + File.separator + "Claims"
                                + File.separator + cla.getClaimId());

                        String filePath = "images/uploads/Claims/" + cla.getClaimId() + "/" + fileName;
                        filePath = filePath.replace("\\", "/");
                        if (!path.exists()) {
                            boolean status = path.mkdirs();
                        }
                        //File uploadedFile = new File(path + "/" + fileName);  // for copy file
                        File uploadedFile = new File(path + "/" + fileName); // for copy file

                        item.write(uploadedFile);
                        isImageExist = true;
                        claims.setAttachment(filePath);//save the url in databse

                    } else {
                        isImageExist = false;

                    }

                } else {

                    fieldName = item.getFieldName();// field name of current File item
                    fieldValue = item.getString();
                    if (fieldName.equals("docid")) {
                        claims.setDocId(Integer.parseInt(fieldValue));
                    } else if (fieldName.equals("claim_group")) {
                        claims.setClaimGroup(fieldValue);
                    } else if (fieldName.equals("type_of_claim")) {//bill type
                        claims.setBillType(fieldValue);
                    } else if (fieldName.equals("food_type")) {//meal type
                        claims.setMealType(fieldValue);
                    } else if (fieldName.equals("bill_date")) {
                        claims.setBillDate(fieldValue);
                    } else if (fieldName.equals("amount")) {
                        claims.setAmount(Double.parseDouble(fieldValue));
                    } else if (fieldName.equals("project")) {
                        claims.setProject(fieldValue);
                    } else if (fieldName.equals("description")) {
                        claims.setDescription(fieldValue);
                    } else if (fieldName.equals("employeesId")) {
                        claims.setEmpListId(fieldValue);
                    }
                    ////////////////////

                }

            } //end of while

            DBcon dbcon = new DBcon();
            dbcon.getDbCon();// set up the database connection
            DBCollection coll = dbcon.getData("claims");

            BasicDBObject search = new BasicDBObject("claimid", cla.getClaimId());
            search.append("details.docid", claims.getDocId());

            DBObject obj = claims.toDBObject();//create DBObject from data

            BasicDBObject update = new BasicDBObject();
            update.append("details.$.claimgroup", claims.getClaimGroup());
            update.append("details.$.billtype", claims.getBillType());
            update.append("details.$.mealtype", claims.getMealType());
            update.append("details.$.bill_date", claims.getBillDate());
            update.append("details.$.amount", claims.getAmount());
            update.append("details.$.project", claims.getProject());
            update.append("details.$.description", claims.getDescription());
            update.append("details.$. employeesId", claims.getEmpListId());
            if (isImageExist) {
                update.append("details.$.attachment", claims.getAttachment());
            }

            BasicDBObject push = new BasicDBObject("$set", update);
            dbcon.updateData("claims", search, push);//update the new document 

            DBCursor cursor = coll.find(search);
            DBObject findMainObject = cursor.next();
            Claims mainClaimObject = Claims.fromDBObject2(findMainObject);//create a main claim object
            ArrayList list = mainClaimObject.getDetails();

            Iterator<BasicDBObject> intI = list.iterator();
            while (intI.hasNext()) {
                BasicDBObject o = intI.next();
                Claims cl = Claims.fromDBObject(o);
                total += cl.getAmount();
            }

            mainClaimObject.setTotal(total);//update the total claim amount*/
            DBObject mainObject = mainClaimObject.toDBObject2();
            dbcon.updateData("claims", search, mainObject);//update the new document    
            response.sendRedirect("home_page_claim_add.jsp");

        } catch (FileUploadException e) {

            e.printStackTrace();
        } catch (Exception e) {

            e.printStackTrace();
        }

    }
}