Example usage for com.mongodb DBCursor close

List of usage examples for com.mongodb DBCursor close

Introduction

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

Prototype

@Override
    public void close() 

Source Link

Usage

From source file:framework.module.users.client.model.DAO.DAO_BD_client.java

/**
 * BD TO ARRAYLIST/*  w  w w. j  av  a 2s. co  m*/
 */
public static void BDtoArray() {
    DBCursor cursor = null;
    String rdo = "";
    Client c1 = new Client();
    try {
        cursor = collection.find().sort(new BasicDBObject("DNI", -1));
        if (cursor.count() != 0) {
            while (cursor.hasNext()) {
                BasicDBObject document = (BasicDBObject) cursor.next();
                c1 = c1.BD_to_Client(document);
                Singleton_client.userclient.add(c1);
            }
        } else {
            System.out.println("NOT DATA");
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:framework.module.users.client.model.DAO.DAO_BD_client.java

/**
 * FIND USER/*  w  w w  .j  av a2 s.c o m*/
 * @param dni 
 */
public static void find_BD(String dni) {
    DBCursor cursor = null;
    String rdo = "";
    try {
        BasicDBObject query = new BasicDBObject("DNI", dni);
        cursor = collection.find(query);
        if (cursor.count() != 0) {
            Singleton_client.client = new Client();
            while (cursor.hasNext()) {
                BasicDBObject document = (BasicDBObject) cursor.next();
                Singleton_client.client = Singleton_client.client.BD_to_Client(document);
            }
        } else {
            Singleton_client.client = null;
            System.out.println("NOT DATA");
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:framework.modules.users.client.Model.DAO.DAO_client_MG.java

/**
 * To load the users by DB/*from www .  j ava2s  . c  o  m*/
 * @param db
 * @param table 
 */
public static void load_clients() {

    DBCollection table = singleton.collection;
    DBCursor cursor = null;
    client_class client = new client_class();
    try {
        cursor = table.find();
        if (cursor.count() != 0) {
            while (cursor.hasNext()) {
                BasicDBObject document = (BasicDBObject) cursor.next();
                singleton_client.client.add(client.DB_to_client(document));
            }
        } else {
            System.out.println("NOT DATA");
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:framework.modules.users.client.Model.DAO.DAO_client_MG.java

public static boolean search_client() {

    DBCollection table = singleton.collection;
    DBCursor cursor = null;
    client_class client = new client_class();
    boolean correct = false;
    try {//w w  w.  java  2s  .c o  m

        BasicDBObject searchById = new BasicDBObject();
        searchById.put("dni", log_in.jt_dni.getText());
        //singleton_client.c=new client_class(log_in.jt_dni.getText());

        cursor = table.find(searchById);
        if (cursor.count() != 0) {
            while (cursor.hasNext()) {
                BasicDBObject document = (BasicDBObject) cursor.next();
                singleton_client.c = client.DB_to_client(document);
                //System.out.println(singleton_client.c);
                correct = true;
                //singleton_client.c.add(client.DB_to_client(document));
            }
        } else {
            System.out.println("NOT DATA");
            correct = false;
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return correct;

}

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   w  w w.  ja va  2s.  co m*/
        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:GeoHazardServices.Inst.java

License:Apache License

private void loadSettings() {

    System.out.println("Load settings...");

    DBCollection coll = db.getCollection("settings");

    DBCursor cursor = coll.find(new BasicDBObject("type", "parameter"));
    for (DBObject obj : cursor) {
        String name = (String) obj.get("name");
        String value = (String) obj.get("value");

        GlobalParameter.map.put(name, value);
        System.out.println("Parameter " + name + ": " + value);
    }//from www. j a v a2s  . c o m
    cursor.close();

    cursor = coll.find(new BasicDBObject("type", "jet_color"));
    for (DBObject obj : cursor) {
        Double threshold = (Double) obj.get("threshold");
        String color = (String) obj.get("color");

        GlobalParameter.jets.put(threshold, color);
        System.out.println("Tsunami-Jet-Threshold " + threshold + ": " + color);
    }
    cursor.close();

    DBObject urls = coll.findOne(new BasicDBObject("type", "urls"));
    GlobalParameter.wsgi_url = (String) urls.get("wsgi");

    int j = 0;

    cursor = coll.find(new BasicDBObject("type", "worker"));
    for (DBObject obj : cursor) {

        String hardware = (String) obj.get("hardware");
        String user = (String) obj.get("user");
        String host = (String) obj.get("host");
        String dir = (String) obj.get("dir");
        String args = (String) obj.get("args");
        /* MongoDB stores all integer values as Long (bug?), so convert back here */
        Integer count = ((Long) obj.get("count")).intValue();
        int priority = ((Long) obj.get("priority")).intValue();
        boolean remote = (boolean) obj.get("remote");
        int slots[] = getSlots(obj.get("slots"), count);

        if (count == null)
            count = 1;

        System.out.print("Worker " + count + "x " + hardware + " @ " + priority);
        if (remote)
            System.out.print(", Remote: " + user + "@" + host + ":" + dir);
        System.out.println(", Args: " + args);

        for (int i = 0; i < count; i++, j++) {

            WorkerThread thread;
            try {
                thread = new WorkerThread(scheduler, mongoClient.getServerAddressList(), db.getName(),
                        GlobalParameter.map.get("localdir") + "/w" + j);
            } catch (IOException e) {
                System.err.println("Error: Could not create worker thread.");
                e.printStackTrace();
                continue;
            }

            thread.setHardware(hardware);
            thread.setArgs(args);
            thread.setRemote(user, host, dir + i);
            thread.setPriority(priority);
            thread.setSlot(slots[i]);

            worker.add(thread);
            thread.start();
        }

    }
    cursor.close();
}

From source file:GeoHazardServices.Inst.java

License:Apache License

private void loadInstitutions() {

    institutions = new HashMap<String, Inst>();

    DBCollection coll = db.getCollection("institutions");

    DBCursor cursor = coll.find();

    for (DBObject obj : cursor) {
        Inst inst = new Inst(obj);
        institutions.put(inst.name, inst);
    }//  ww  w  . ja  va 2  s  . c  o m

    cursor.close();
}

From source file:GeoHazardServices.Inst.java

License:Apache License

@POST
@Path("/data_insert")
@Produces(MediaType.APPLICATION_JSON)/*from   w  w w  .j  av a2 s .  co  m*/
public String data_insert(@Context HttpServletRequest request, @FormParam("inst") String inst,
        @FormParam("secret") String secret, @FormParam("id") String id, @FormParam("name") String name,
        @FormParam("lon") Double lon, @FormParam("lat") Double lat, @FormParam("mag") Double mag,
        @FormParam("slip") Double slip, @FormParam("length") Double length, @FormParam("width") Double width,
        @FormParam("depth") Double depth, @FormParam("dip") Double dip, @FormParam("strike") Double strike,
        @FormParam("rake") Double rake, @FormParam("date") String dateStr,
        @FormParam("sea_area") String sea_area, @FormParam("root") String root,
        @FormParam("parent") String parent, @FormParam("comp") Integer comp, @FormParam("accel") Integer accel,
        @FormParam("gridres") Integer gridres, @FormParam("apikey") String apikey,
        @FormParam("algo") @DefaultValue("easywave") String algo) {

    /* Check for invalid parameter configurations. */
    if ((inst != null || secret != null) && apikey != null)
        return jsfailure("Don't mix 'apikey' and 'secret'.");

    if (mag != null && (slip != null || length != null || width != null))
        return jsfailure("Don't mix 'mag' with 'slip', 'length' and 'width'.");

    /* Support 'inst' and 'secret' for compatibility reasons. */
    if (inst != null && secret != null) {
        /* Obtain the 'apikey' and pretend a call to the new api. */
        DBObject query = new BasicDBObject("name", inst).append("secret", secret);
        DBObject tmp_inst = db.getCollection("institutions").findOne(query);
        if (tmp_inst == null)
            return jsdenied();
        apikey = (String) ((DBObject) tmp_inst.get("api")).get("key");
        if (apikey == null)
            return jsfailure("No 'apikey' set for this institution!");
    }

    /* Continue with the new API. */
    Object[] required = { apikey, id, name, dateStr };

    if (!checkParams(request, required))
        return jsfailure();

    DBObject db_user = auth_api(apikey, "user");
    DBObject db_inst = auth_api(apikey, "inst");

    /* check if we got a valid institution and the correct secret */
    ObjectId user_id;
    String user_name;
    User user;
    if (db_user != null) {
        user_id = (ObjectId) db_user.get("_id");
        user_name = (String) db_user.get("username");
        user = new User(db_user, getInst(db_user));
    } else if (db_inst != null) {
        user_id = (ObjectId) db_inst.get("_id");
        user_name = (String) db_inst.get("name");
        user = new Inst(db_inst);
    } else {
        return jsdenied();
    }

    System.out.println(user.name + " - " + user.inst);

    /* get Date object from date string */
    System.out.println(dateStr);
    Date date = parseIsoDate(dateStr);
    if (date == null)
        return jsfailure("Invalid date format.");

    System.out.println(id);

    /* get current timestamp */
    Date timestamp = new Date();

    /* create new sub object that stores the properties */
    BasicDBObject sub = new BasicDBObject();
    sub.put("date", date);
    sub.put("region", name);
    sub.put("latitude", lat);
    sub.put("longitude", lon);
    sub.put("magnitude", mag);
    sub.put("slip", slip);
    sub.put("length", length);
    sub.put("width", width);
    sub.put("depth", depth);
    sub.put("dip", dip);
    sub.put("strike", strike);
    sub.put("rake", rake);
    sub.put("sea_area", sea_area);

    if (accel == null)
        accel = 1;

    /* create new DB object that should be added to the eqs collection */
    BasicDBObject obj = new BasicDBObject();
    obj.put("id", id);
    obj.put("user", user_id);
    obj.put("timestamp", timestamp);
    obj.put("prop", sub);
    obj.put("root", root);
    obj.put("parent", parent);
    obj.put("accel", accel);
    //obj.put( "gridres", gridres );

    /* create a new event */
    BasicDBObject event = new BasicDBObject();
    event.put("user", user_id);
    event.put("timestamp", timestamp);
    event.put("event", "new");

    Long refineId = 0L;

    /* get earthquake collection */
    DBCollection coll = db.getCollection("eqs");
    /* search for given id */
    BasicDBObject inQuery = new BasicDBObject("id", id).append("user", user_id);
    DBCursor cursor = coll.find(inQuery).sort(new BasicDBObject("refineId", -1));

    BasicDBObject entry = null;

    /* if id is already used, make a refinement */
    if (cursor.hasNext()) {

        /* get properties of returned entry */
        entry = (BasicDBObject) cursor.next();

        /* update entry ID in database by appending deprecated field */
        BasicDBObject depr = new BasicDBObject("depr", true);
        coll.update(entry, new BasicDBObject("$set", depr));

        refineId = (Long) entry.get("refineId");

        if (refineId == null) {
            refineId = new Long(0);
        }

        refineId++;

        /* override parent and root attributes */
        root = entry.get("root") == null ? (String) entry.get("_id") : (String) entry.get("root");
        obj.put("root", root);
        obj.put("parent", entry.get("_id"));

        /* override event type */
        event.put("event", "update");
    }

    /* set refinement and compound Ids */
    final CompId compId = new CompId(user_name, id, refineId);
    obj.put("_id", compId.toString());
    obj.put("refineId", refineId);
    event.put("id", compId.toString());

    /* clean up query */
    cursor.close();

    /* insert object into 'eqs' collection */
    coll.insert(obj);

    System.out.println(obj);

    Object[] reqComp1 = { id, lon, lat, mag, depth, dip, strike, rake };
    Object[] reqComp2 = { id, lon, lat, slip, length, width, depth, dip, strike, rake };
    boolean simulate = comp != null && (checkParams(request, reqComp1) || checkParams(request, reqComp2));

    /* insert new event into 'events'-collection */
    db.getCollection("events").insert(event);

    System.out.println(simulate);

    if (simulate)
        //computeById( request, null, null, id, refineId, comp, accel, apikey );
        _computeById(user, compId.toString(), comp, accel, gridres, algo);
    else
        /* run request in a separate thread to avoid blocking */
        new Thread() {
            public void run() {
                sendPost(GlobalParameter.wsgi_url + "webguisrv/post_compute", "evtid=" + compId.toString());
            }
        }.start();

    return jssuccess(new BasicDBObject("refineId", refineId).append("evtid", compId.toString()));
}

From source file:GeoHazardServices.Inst.java

License:Apache License

private DBObject getUserObj(String username) {

    DBCollection coll = db.getCollection("users");

    DBCursor cursor = coll.find(new BasicDBObject("username", username));

    if (!cursor.hasNext())
        return null;

    DBObject obj = cursor.next();/*  w ww  .  j  a  v  a 2s.c o m*/
    cursor.close();

    BasicDBObject userObj = new BasicDBObject("username", obj.get("username"));
    userObj.put("_id", obj.get("_id"));
    userObj.put("permissions", obj.get("permissions"));
    userObj.put("properties", obj.get("properties"));
    userObj.put("notify", obj.get("notify"));
    userObj.put("api", obj.get("api"));

    ObjectId instId = (ObjectId) obj.get("inst");

    cursor = db.getCollection("institutions").find(new BasicDBObject("_id", instId));

    String instName = null;

    if (cursor.hasNext()) {

        DBObject inst = cursor.next();
        inst.removeField("_id");
        inst.removeField("secret");
        userObj.put("inst", inst);
        instName = (String) inst.get("name");
    }

    cursor.close();

    if (instName == null || instName.equals("gfz") || instName.equals("tdss15"))
        instName = "gfz_ex_test";

    /* get all available country codes and count elements in each group */
    DBObject groupFields = new BasicDBObject("_id", "$country");
    groupFields.put("count", new BasicDBObject("$sum", 1));

    DBObject group = new BasicDBObject("$group", groupFields);

    BasicDBList types = new BasicDBList();
    types.add(new BasicDBObject("sensor", "rad"));
    types.add(new BasicDBObject("sensor", "prs"));
    types.add(new BasicDBObject("sensor", "pr1"));
    types.add(new BasicDBObject("sensor", "flt"));
    types.add(new BasicDBObject("sensor", null));

    DBObject filterFields = new BasicDBObject("$or", types);

    BasicDBList andList = new BasicDBList();
    andList.add(filterFields);
    andList.add(new BasicDBObject("inst", instName));

    DBObject andObj = new BasicDBObject("$and", andList);
    DBObject filter = new BasicDBObject("$match", andObj);

    /* sort alphabetically */
    DBObject sortFields = new BasicDBObject("_id", 1);
    DBObject sort = new BasicDBObject("$sort", sortFields);

    AggregationOutput output = db.getCollection("stations").aggregate(filter, group, sort);
    BasicDBList countries = new BasicDBList();

    /* convert answer into string list */
    @SuppressWarnings("unchecked")
    List<String> clist = (List<String>) obj.get("countries");

    for (DBObject res : output.results()) {
        String code = (String) res.get("_id");
        if (code == null)
            continue;
        boolean isOn = (clist != null) && clist.contains(code);
        res.put("on", isOn);
        countries.add(res);
    }

    userObj.put("countries", countries);

    return userObj;
}

From source file:GeoHazardServices.Inst.java

License:Apache License

private User signedIn(String session) {

    if (session == null)
        return null;

    DBCollection coll = db.getCollection("users");
    DBCollection insts = db.getCollection("institutions");

    DBCursor cursor = coll.find(new BasicDBObject("session", session));
    DBObject obj;// w  ww  . j  av  a2  s  .c  om
    DBObject inst = null;

    if (cursor.hasNext()) {

        /* we have found a valid session key */
        obj = cursor.next();
        cursor.close();

        cursor = insts.find(new BasicDBObject("_id", obj.get("inst")));
        if (cursor.hasNext())
            inst = cursor.next();

        return new User(obj, inst);
    }

    return null;
}