Example usage for com.mongodb BasicDBObject getString

List of usage examples for com.mongodb BasicDBObject getString

Introduction

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

Prototype

public String getString(final String key) 

Source Link

Document

Returns the value of a field as a string

Usage

From source file:org.slc.sli.ingestion.util.MongoCommander.java

License:Apache License

/**
 * get list of  the shards// w ww . j a  v  a  2 s.  co m
 * @param dbConn
 * @return
 */
private static List<String> getShards(DB dbConn) {
    List<String> shards = new ArrayList<String>();

    DBObject listShardsCmd = new BasicDBObject("listShards", 1);
    CommandResult res = dbConn.command(listShardsCmd);
    if (!res.ok()) {
        LOG.error("Error getting shards for {}: {}", dbConn, res.getErrorMessage());
    }

    BasicDBList listShards = (BasicDBList) res.get("shards");

    //Only get shards for sharding mongo
    if (listShards != null) {
        ListIterator<Object> iter = listShards.listIterator();

        while (iter.hasNext()) {
            BasicDBObject shard = (BasicDBObject) iter.next();
            shards.add(shard.getString(ID));
        }
    }
    return shards;
}

From source file:org.z.core.es.plugins.memorystore.newDragonDict.java

License:Apache License

public static void init() {
    logger.info(" init ...");
    DBCursor stock = MongodbUtils.getColl(Config.getField("db.dragon.coll", "stock"))
            .find(new BasicDBObject().append("c", "all"));

    BasicDBObject st = null;
    while (stock.hasNext()) {
        st = (BasicDBObject) stock.next();
        dragonMap.put(st.getString("s").trim(), "1");
    }/* w  ww .  ja  v  a2 s.co  m*/
    DBCursor stockn = MongodbUtils.getColl(Config.getField("db.dragon.coll", "stock")).find(
            new BasicDBObject().append("c", new BasicDBObject().append("$ne", "all")),
            new BasicDBObject().append("s", 1));
    while (stockn.hasNext()) {
        st = (BasicDBObject) stockn.next();
        dragonMap.put(st.getString("s").trim() + "n", "1");
    }

    logger.info(" init done! size: " + dragonMap.size() + " collection "
            + Config.getField("db.dragon.coll", "stock"));
}

From source file:org.zeus.HealthEnhancements.ProviderInfo.java

private ProviderInfo(BasicDBObject dbObject) {
    m_id = ((ObjectId) dbObject.get("_id")).toString();
    m_szUserName = dbObject.getString("m_szUserName");
    m_szHashUserPassword = dbObject.getString("m_szHashUserPassword");
    m_szProviderType = dbObject.getString("m_szProviderType");
    m_szFirstName = dbObject.getString("m_szFirstName");
    m_szLastName = dbObject.getString("m_szLastName");
    m_szMiddleName = dbObject.getString("m_szMiddleName");
    m_szSocialSecurity = dbObject.getString("m_szSocialSecurity");
    m_szLicenseNumber = dbObject.getString("m_szLicenseNumber");
    m_szPersonnelType = dbObject.getString("m_szPersonnelType");
    m_szSpecialization = dbObject.getString("m_szSpecialization");
    m_szAffiliation = dbObject.getString("m_szAffiliation");
    m_szAddress = dbObject.getString("m_szAddress");
    m_szPhoneNumber = dbObject.getString("m_szPhoneNumber");
    m_szEmail = dbObject.getString("m_szEmail");
}

From source file:pl.nask.hsn2.os.ObjectStore.java

License:Open Source License

public ObjectStoreResponse updateObject(ObjectRequest objectRequest) {

    try {//  w  w  w.  jav  a 2  s.  c o m
        ObjectStoreResponse response = new ObjectStoreResponse(ResponseType.SUCCESS_UPDATE);
        List<ObjectData> dataList = objectRequest.getDataList();
        boolean overwrite = objectRequest.getOverwrite();

        ArrayList<Long> ids = new ArrayList<Long>();
        for (ObjectData objectData : dataList) {
            ids.add(objectData.getId());
        }

        ArrayList<BasicDBObject> resultGet = mongoConnector.getObjById(objectRequest.getJob(), ids);
        if (resultGet.size() < dataList.size()) {
            response.setType(ResponseType.PARTIAL_UPDATE);
        }

        for (ObjectData obj : dataList) {
            BasicDBObject tmp = null;
            for (BasicDBObject dbObject : resultGet) {
                if (Long.parseLong(dbObject.getString("_id")) == obj.getId()) {
                    tmp = dbObject;
                    break;
                }
            }

            if (tmp == null) {
                response.addMissing(obj.getId());
            } else {
                for (Attribute attr : obj.getAttrsList()) {
                    EntityAttribute eattr = EntityAttribute.instanceFor(attr);
                    if (tmp.containsField(attr.getName())) {
                        response.addConflict(Long.parseLong(tmp.getString("_id")));
                        if (overwrite) {
                            tmp.put(attr.getName(), eattr.getValue());
                        }
                    } else {
                        tmp.put(attr.getName(), eattr.getValue());
                    }
                }
                mongoConnector.saveObject(tmp);
            }
        }

        return response;
    } catch (IllegalStateException e) {
        LOGGER.error("Object request: {}", objectRequest);
        throw e;
    }
}

From source file:pl.nask.hsn2.os.ObjectStore.java

License:Open Source License

private Builder getBuilder(String key, BasicDBObject objectFound) {
    Object value = objectFound.get(key);
    Builder builder = Attribute.newBuilder().setName(key);

    if (value instanceof Integer || key.equalsIgnoreCase("depth")) {
        builder.setType(Type.INT).setDataInt(objectFound.getInt(key));
    } else if (value instanceof Long) {
        builder.setType(Type.OBJECT).setDataObject(objectFound.getLong(key));
    } else if (value instanceof BasicDBObject) {

        BasicDBObject mongoObj = (BasicDBObject) value;
        if (mongoObj.get("type").equals("TIME")) {
            builder.setType(Type.TIME).setDataTime(mongoObj.getLong("time"));
        } else if (mongoObj.get("type").equals("BYTES")) {
            builder.setType(Type.BYTES).setDataBytes(Reference.newBuilder().setKey(mongoObj.getLong("key"))
                    .setStore(mongoObj.getInt("store")).build());
        }//from  w ww. java 2 s.c o m
    } else if (value instanceof Boolean) {
        builder.setType(Type.BOOL).setDataBool(objectFound.getBoolean(key));
    } else {
        builder.setType(Type.STRING).setDataString(objectFound.getString(key));
    }
    return builder;
}

From source file:poke.resources.JobResource.java

License:Apache License

@Override
public Request process(Request request) {

    Request reply = null;/* w ww. ja v a  2  s  .  com*/

    String leaderId = ElectionManager.getInstance().getLeader();

    if (Server.getMyId().equals(leaderId)) {
        // Reply processing only done by the leader

        if (request.getBody().hasJobStatus()) {

            logger.info("\n**********\nRECEIVED JOB STATUS" + "\n\n**********");

            // JobStatus
            String jobId = request.getBody().getJobStatus().getJobId();
            logger.info("JobStatus.JobId: " + jobId + "\n");
            if (requestMap.containsKey(jobId)) {
                requestMap.remove(jobId);
                Channel ch = chMap.get(jobId);
                chMap.remove(jobId);
                ch.writeAndFlush(request);
            }

        } else if (request.getBody().hasJobOp()) {
            logger.info("\n**********\n LEADER RECEIVED NEW JOB REQUEST" + "\n\n**********");
            logger.info("\n**********\n CREATING A JOB PROPOSAL" + "\n\n**********");

            // Job proposal

            JobOperation jobOp = request.getBody().getJobOp();

            logger.info("\n**********JobOperation.JobId: " + jobOp.getJobId() + "\n\n**********");
            requestMap.put(jobOp.getJobId(), request);

            Management.Builder mb = Management.newBuilder();
            JobProposal.Builder jbr = JobProposal.newBuilder();
            jbr.setJobId(jobOp.getJobId());
            jbr.setNameSpace(jobOp.getData().getNameSpace());
            jbr.setOwnerId(jobOp.getData().getOwnerId());
            jbr.setWeight(5);

            mb.setJobPropose(jbr.build());

            Management jobProposal = mb.build();

            String destHost = null;
            int destPort = 0;

            if (jobOp.getData().getNameSpace().equals(getMoreCourses)
                    || jobOp.getData().getNameSpace().equals(competition)) {

                // This arraylist contains IP addresses of all leaders of
                // other clusters

                List<String> leaderList = new ArrayList<String>();

                // leaderList.add(new String("192.168.0.61:5670"));
                // leaderList.add(new String("192.168.0.60:5673"));
                // leaderList.add(new String("192.168.0.230:5573"));

                for (String destination : leaderList) {
                    String[] dest = destination.split(":");
                    destHost = dest[0];
                    destPort = Integer.parseInt(dest[1]);

                    InetSocketAddress sa = new InetSocketAddress(destHost, destPort);

                    Channel ch = connectToManagement(sa);
                    ch.writeAndFlush(jobProposal);

                    logger.info("\n**********Job proposal sent\n\n**********");
                }

            } else {

                for (NodeDesc nn : configFile.getNearest().getNearestNodes().values()) {
                    destHost = nn.getHost();
                    destPort = nn.getMgmtPort();

                    InetSocketAddress sa = new InetSocketAddress(destHost, destPort);

                    Channel ch = connectToManagement(sa);
                    ch.writeAndFlush(jobProposal);
                    logger.info("\n**********Job proposal sent\n\n**********");

                }

            }

        }

    }

    else {
        // Done by only a slave node
        logger.info("\n**********\n RECEIVED NEW JOB REQUEST" + "\n\n**********");

        JobOperation jobOp = request.getBody().getJobOp();

        if (jobOp.hasAction()) {

            JobAction jobAction = request.getBody().getJobOp().getAction();

            if (jobAction.equals(JobAction.ADDJOB)) {

                logger.info("ADDJOB received");

                // check if it is signUp
                if (signUp.equals(jobOp.getData().getNameSpace())) {
                    // sign up
                    logger.info("it is a sign up job");

                    HashMap<String, String> credentials = new HashMap<String, String>();
                    NameValueSet nvSet = jobOp.getData().getOptions();
                    List<NameValueSet> nvList = null;

                    if (nvSet != null) {
                        nvList = nvSet.getNodeList();
                    }
                    String email, password, firstName, lastName;
                    email = password = firstName = lastName = null;
                    for (NameValueSet nvPair : nvList) {
                        credentials.put(nvPair.getName(), nvPair.getValue());
                        if (nvPair.getName().equals("email"))
                            email = nvPair.getValue();
                        if (nvPair.getName().equals("firstName"))
                            firstName = nvPair.getValue();
                        if (nvPair.getName().equals("lastName"))
                            lastName = nvPair.getValue();
                        if (nvPair.getName().equals("password"))
                            password = nvPair.getValue();
                    }
                    MongoStorage.addUser(email, password, firstName, lastName);
                    logger.info("credentials: " + credentials.toString());

                    // reply success
                    Request.Builder rb = Request.newBuilder();
                    // metadata
                    rb.setHeader(ResourceUtil.buildHeader(request.getHeader().getRoutingId(),
                            PokeStatus.SUCCESS, "sign up successful", request.getHeader().getOriginator(),
                            request.getHeader().getTag(), leaderId));

                    // payload
                    Payload.Builder pb = Payload.newBuilder();
                    JobStatus.Builder jb = JobStatus.newBuilder();
                    jb.setStatus(PokeStatus.SUCCESS);
                    jb.setJobId(jobOp.getJobId());
                    jb.setJobState(JobDesc.JobCode.JOBRECEIVED);
                    JobDesc.Builder jd = JobDesc.newBuilder();
                    jd.setNameSpace("result");
                    jd.setOwnerId(MongoStorage.getUserID(email));
                    jd.setJobId(jobOp.getJobId());
                    jd.setStatus(JobDesc.JobCode.JOBRECEIVED);
                    jb.addData(jd.build());
                    pb.setJobStatus(jb.build());

                    rb.setBody(pb.build());

                    reply = rb.build();

                } else if (logIn.equals(jobOp.getData().getNameSpace())) {
                    // login

                    if (jobOp.getData().getOptions() != null) {
                        HashMap<String, String> credentials = new HashMap<String, String>();
                        NameValueSet nvSet = jobOp.getData().getOptions();
                        List<NameValueSet> nvList = null;

                        if (nvSet != null) {
                            nvList = nvSet.getNodeList();
                        }
                        String email, password;
                        email = password = null;
                        for (NameValueSet nvPair : nvList) {
                            credentials.put(nvPair.getName(), nvPair.getValue());
                            if (nvPair.getName().equals("email"))
                                email = nvPair.getValue();
                            if (nvPair.getName().equals("password"))
                                password = nvPair.getValue();
                        }
                        logger.info("#######Credentials: " + credentials.toString() + "#######");

                        // reply success
                        Request.Builder rb = Request.newBuilder();
                        // metadata

                        // payload
                        Payload.Builder pb = Payload.newBuilder();
                        JobStatus.Builder jb = JobStatus.newBuilder();
                        jb.setStatus(PokeStatus.SUCCESS);
                        jb.setJobId(jobOp.getJobId());
                        jb.setJobState(JobDesc.JobCode.JOBRECEIVED);
                        int owner = 666;
                        String message = "Login Successful";
                        if (!MongoStorage.validateUser(email, password)) {
                            message = "Login Failed";
                            jb.setStatus(PokeStatus.FAILURE);
                        } else {
                            owner = MongoStorage.getUserID(email);
                        }
                        JobDesc.Builder jd = JobDesc.newBuilder();
                        jd.setNameSpace("result");
                        jd.setOwnerId(owner);
                        jd.setJobId(jobOp.getJobId());
                        jd.setStatus(JobDesc.JobCode.JOBRECEIVED);
                        jb.addData(jd.build());
                        pb.setJobStatus(jb.build());
                        rb.setBody(pb.build());
                        rb.setHeader(ResourceUtil.buildHeader(request.getHeader().getRoutingId(),
                                PokeStatus.SUCCESS, message, request.getHeader().getOriginator(),
                                request.getHeader().getTag(), leaderId));
                        reply = rb.build();
                    }

                } else if (getDescription.equals(jobOp.getData().getNameSpace())) {
                    // login

                    if (jobOp.getData().getOptions() != null) {
                        NameValueSet nvSet = jobOp.getData().getOptions();

                        String cName = null;
                        if (nvSet != null) {
                            if (nvSet.getName().equals("coursename"))
                                cName = nvSet.getValue();
                        }
                        BasicDBObject result = MongoStorage.getCourseByName(cName);

                        // reply success
                        Request.Builder rb = Request.newBuilder();
                        // metadata

                        // payload
                        Payload.Builder pb = Payload.newBuilder();
                        JobStatus.Builder jb = JobStatus.newBuilder();
                        jb.setStatus(PokeStatus.SUCCESS);
                        jb.setJobId(jobOp.getJobId());
                        jb.setJobState(JobDesc.JobCode.JOBRECEIVED);
                        JobDesc.Builder jd = JobDesc.newBuilder();
                        jd.setNameSpace("result");
                        jd.setOwnerId(jobOp.getData().getOwnerId());
                        jd.setJobId(jobOp.getJobId());
                        jd.setStatus(JobDesc.JobCode.JOBRECEIVED);
                        NameValueSet.Builder nv = NameValueSet.newBuilder();
                        nv.setNodeType(NameValueSet.NodeType.VALUE);
                        nv.setName("coursedescription");

                        String desc = "";
                        String message = "Course Description Attached";
                        if (result == null) {
                            message = "Course Not Found";
                            jb.setStatus(PokeStatus.FAILURE);
                        } else
                            desc = result.getString("desc");
                        nv.setValue(desc);
                        jd.setOptions(nv.build());
                        jb.addData(jd.build());
                        pb.setJobStatus(jb.build());
                        rb.setBody(pb.build());
                        rb.setHeader(ResourceUtil.buildHeader(request.getHeader().getRoutingId(),
                                PokeStatus.SUCCESS, message, request.getHeader().getOriginator(),
                                request.getHeader().getTag(), leaderId));
                        reply = rb.build();
                    }

                } else if (listCourses.equals(jobOp.getData().getNameSpace())
                        || getMoreCourses.equals(jobOp.getData().getNameSpace())) {
                    // list all courses

                    if (jobOp.getData().getOptions() != null) {
                        List<DBObject> dbObj = new ArrayList<DBObject>();
                        // TODO this method has to be changed
                        dbObj = MongoStorage.getAllCourses();
                        String val = "";
                        NameValueSet.Builder courses = NameValueSet.newBuilder();
                        courses.setNodeType(NameValueSet.NodeType.VALUE);
                        courses.setName(listCourses);
                        courses.setValue("attached");
                        for (int i = 0; i < dbObj.size(); i++) {
                            BasicDBObject result2 = (BasicDBObject) dbObj.get(i);
                            val = result2.getString("name");
                            if (val != null) {
                                logger.info("this is Courses" + val);
                                NameValueSet.Builder cb = NameValueSet.newBuilder();
                                cb.setNodeType(NameValueSet.NodeType.NODE);
                                cb.setName("" + result2.getString("cId"));
                                cb.setValue(val);
                                courses.addNode(cb.build());
                            }
                        }
                        // reply success
                        Request.Builder rb = Request.newBuilder();
                        // metadata
                        rb.setHeader(ResourceUtil.buildHeader(request.getHeader().getRoutingId(),
                                PokeStatus.SUCCESS, "listing successful", request.getHeader().getOriginator(),
                                request.getHeader().getTag(), leaderId));

                        // payload
                        Payload.Builder pb = Payload.newBuilder();
                        JobStatus.Builder jb = JobStatus.newBuilder();
                        jb.setStatus(PokeStatus.SUCCESS);
                        jb.setJobId(jobOp.getJobId());
                        jb.setJobState(JobDesc.JobCode.JOBRECEIVED);
                        JobDesc.Builder jDescBuilder = JobDesc.newBuilder();
                        jDescBuilder.setJobId(jobOp.getJobId());
                        jDescBuilder.setNameSpace(listCourses);
                        jDescBuilder.setOwnerId(jobOp.getData().getOwnerId());
                        jDescBuilder.setStatus(JobCode.JOBRECEIVED);
                        jDescBuilder.setOptions(courses.build());
                        jb.addData(jDescBuilder.build());
                        pb.setJobStatus(jb.build());
                        rb.setBody(pb.build());
                        reply = rb.build();
                    }

                } else if (competition.equals(jobOp.getData().getNameSpace())) {

                    // reply success
                    Request.Builder rb = Request.newBuilder();
                    // metadata
                    rb.setHeader(ResourceUtil.buildHeader(request.getHeader().getRoutingId(),
                            PokeStatus.SUCCESS, "competition request processed",
                            request.getHeader().getOriginator(), request.getHeader().getTag(), leaderId));

                    // payload
                    Payload.Builder pb = Payload.newBuilder();
                    JobStatus.Builder jb = JobStatus.newBuilder();
                    jb.setStatus(PokeStatus.SUCCESS);
                    jb.setJobId(jobOp.getJobId());
                    jb.setJobState(JobDesc.JobCode.JOBRECEIVED);
                    pb.setJobStatus(jb.build());

                    rb.setBody(pb.build());

                    reply = rb.build();

                } else if (addQuestion.equals(jobOp.getData().getNameSpace())) {

                    if (jobOp.getData().getOptions() != null) {
                        List<NameValueSet> nvList = jobOp.getData().getOptions().getNodeList();

                        HashMap<String, String> credentials = new HashMap<String, String>();
                        int iowner = 0;
                        for (NameValueSet nvPair : nvList) {
                            credentials.put(nvPair.getName(), nvPair.getValue());
                        }
                        logger.info("#######Credentials: " + credentials.toString() + "#######");
                        String title, owner, description, postdate;

                        title = description = postdate = owner = null;

                        for (NameValueSet nvPair : nvList) {
                            credentials.put(nvPair.getName(), nvPair.getValue());
                            if (nvPair.getName().equals("title"))
                                title = nvPair.getValue();
                            if (nvPair.getName().equals("owner"))
                                iowner = Integer.parseInt(nvPair.getValue());
                            if (nvPair.getName().equals("description"))
                                description = nvPair.getValue();
                            if (nvPair.getName().equals("postdate"))
                                postdate = nvPair.getValue();
                        }
                        MongoStorage.addQuestion(title, iowner, description, postdate);

                        // reply success
                        Request.Builder rb = Request.newBuilder();
                        // metadata
                        rb.setHeader(ResourceUtil.buildHeader(request.getHeader().getRoutingId(),
                                PokeStatus.SUCCESS, "question added", request.getHeader().getOriginator(),
                                request.getHeader().getTag(), leaderId));

                        // payload
                        Payload.Builder pb = Payload.newBuilder();
                        JobStatus.Builder jb = JobStatus.newBuilder();
                        jb.setStatus(PokeStatus.SUCCESS);
                        jb.setJobId(jobOp.getJobId());
                        jb.setJobState(JobDesc.JobCode.JOBRECEIVED);
                        pb.setJobStatus(jb.build());

                        rb.setBody(pb.build());

                        reply = rb.build();

                    }
                } else if (showQuestion.equals(jobOp.getData().getNameSpace())) {

                    if (jobOp.getData().getOptions() != null) {
                        List<String> list = new ArrayList<String>();
                        List<DBObject> dbObj = new ArrayList<DBObject>();

                        dbObj = MongoStorage.getAllQuestions();
                        NameValueSet.Builder questions = NameValueSet.newBuilder();
                        questions.setNodeType(NameValueSet.NodeType.VALUE);
                        questions.setName(showQuestion);
                        questions.setValue("attached");
                        String val = "";
                        for (int i = 0; i < dbObj.size(); i++) {
                            BasicDBObject result2 = (BasicDBObject) dbObj.get(i);
                            val = result2.getString("description");
                            if (val != null) {
                                NameValueSet.Builder cb = NameValueSet.newBuilder();
                                cb.setNodeType(NameValueSet.NodeType.NODE);
                                cb.setName("" + result2.getString("qId"));
                                cb.setValue(val);
                                questions.addNode(cb.build());
                            }

                        }

                        for (int i = 0; i < list.size(); i++) {

                            logger.info("Question" + list.get(i));
                            NameValueSet.Builder cb = NameValueSet.newBuilder();
                            cb.setNodeType(NameValueSet.NodeType.NODE);
                            cb.setName("Question");
                            cb.setValue(list.get(i));
                            // cb.build();
                            questions.addNode(cb.build());
                        }

                        // reply success
                        Request.Builder rb = Request.newBuilder();
                        // metadata
                        rb.setHeader(ResourceUtil.buildHeader(request.getHeader().getRoutingId(),
                                PokeStatus.SUCCESS, "Questions Retrieved", request.getHeader().getOriginator(),
                                request.getHeader().getTag(), leaderId));

                        // payload
                        Payload.Builder pb = Payload.newBuilder();
                        JobStatus.Builder jb = JobStatus.newBuilder();
                        jb.setStatus(PokeStatus.SUCCESS);
                        jb.setJobId(jobOp.getJobId());
                        jb.setJobState(JobDesc.JobCode.JOBRECEIVED);
                        JobDesc.Builder jDescBuilder = JobDesc.newBuilder();
                        jDescBuilder.setJobId(jobOp.getJobId());
                        jDescBuilder.setNameSpace(listCourses);
                        jDescBuilder.setOwnerId(jobOp.getData().getOwnerId());
                        jDescBuilder.setStatus(JobCode.JOBRECEIVED);

                        jDescBuilder.setOptions(questions.build());
                        // set courseList using jDescBuilder.setOptions()
                        jb.addData(jDescBuilder.build());
                        pb.setJobStatus(jb.build());
                        rb.setBody(pb.build());
                        reply = rb.build();
                    }
                } else if (addAnswer.equals(jobOp.getData().getNameSpace())) {

                    if (jobOp.getData().getOptions() != null) {
                        List<NameValueSet> nvList = jobOp.getData().getOptions().getNodeList();

                        HashMap<String, String> credentials = new HashMap<String, String>();
                        for (NameValueSet nvPair : nvList) {
                            credentials.put(nvPair.getName(), nvPair.getValue());
                        }
                        logger.info("#######Credentials: " + credentials.toString() + "#######");
                        String description = null;
                        int uId, qId;
                        uId = qId = 0;
                        for (NameValueSet nvPair : nvList) {
                            credentials.put(nvPair.getName(), nvPair.getValue());
                            if (nvPair.getName().equals("uId"))
                                uId = Integer.parseInt(nvPair.getValue());
                            if (nvPair.getName().equals("qId"))
                                qId = Integer.parseInt(nvPair.getValue());
                            if (nvPair.getName().equals("description"))
                                description = nvPair.getValue();
                        }
                        MongoStorage.addAnswer(uId, qId, description);

                        // reply success
                        Request.Builder rb = Request.newBuilder();
                        // metadata
                        rb.setHeader(ResourceUtil.buildHeader(request.getHeader().getRoutingId(),
                                PokeStatus.SUCCESS, "Answer added", request.getHeader().getOriginator(),
                                request.getHeader().getTag(), leaderId));

                        // payload
                        Payload.Builder pb = Payload.newBuilder();
                        JobStatus.Builder jb = JobStatus.newBuilder();
                        jb.setStatus(PokeStatus.SUCCESS);
                        jb.setJobId(jobOp.getJobId());
                        jb.setJobState(JobDesc.JobCode.JOBRECEIVED);
                        pb.setJobStatus(jb.build());

                        rb.setBody(pb.build());

                        reply = rb.build();

                    }
                } else if (showAnswer.equals(jobOp.getData().getNameSpace())) {

                    if (jobOp.getData().getOptions() != null) {
                        List<DBObject> dbObj = new ArrayList<DBObject>();

                        dbObj = MongoStorage.getAllAnswer();
                        String val = "";
                        NameValueSet.Builder questions = NameValueSet.newBuilder();
                        questions.setNodeType(NameValueSet.NodeType.VALUE);
                        questions.setName(showAnswer);
                        questions.setValue("attached");
                        for (int i = 0; i < dbObj.size(); i++) {
                            BasicDBObject result2 = (BasicDBObject) dbObj.get(i);
                            val = result2.getString("description");
                            if (val != null) {
                                NameValueSet.Builder cb = NameValueSet.newBuilder();
                                cb.setNodeType(NameValueSet.NodeType.NODE);
                                cb.setName("" + result2.getString("qId"));
                                cb.setValue(val);
                                questions.addNode(cb.build());
                            }
                        }
                        // reply success
                        Request.Builder rb = Request.newBuilder();
                        // metadata
                        rb.setHeader(ResourceUtil.buildHeader(request.getHeader().getRoutingId(),
                                PokeStatus.SUCCESS, "Answers Retrieved", request.getHeader().getOriginator(),
                                request.getHeader().getTag(), leaderId));

                        // payload
                        Payload.Builder pb = Payload.newBuilder();
                        JobStatus.Builder jb = JobStatus.newBuilder();
                        jb.setStatus(PokeStatus.SUCCESS);
                        jb.setJobId(jobOp.getJobId());
                        jb.setJobState(JobDesc.JobCode.JOBRECEIVED);
                        JobDesc.Builder jDescBuilder = JobDesc.newBuilder();
                        jDescBuilder.setJobId(jobOp.getJobId());
                        jDescBuilder.setNameSpace(addAnswer);
                        jDescBuilder.setOwnerId(jobOp.getData().getOwnerId());
                        jDescBuilder.setStatus(JobCode.JOBRECEIVED);

                        jDescBuilder.setOptions(questions.build());
                        jb.addData(jDescBuilder.build());
                        pb.setJobStatus(jb.build());
                        rb.setBody(pb.build());
                        reply = rb.build();
                    }
                }

            }
        }
    }

    return reply;

}

From source file:pt.tiago.mongodbteste.MongoDB.java

private void search() {
    //search all... select * from
    DBCursor cursor = collection.get(1).find();
    while (cursor.hasNext()) {
        DBObject obj = cursor.next();/*from   ww w  .  jav a  2 s. com*/
        BasicDBObject basicObj = (BasicDBObject) obj;
        Person person = new Person();
        person.setID(String.valueOf(basicObj.getObjectId("_id")));
        person.setName(basicObj.getString("name"));
        person.setSurname(basicObj.getString("surname"));
        System.out.println(person.toString());
    }

    //Select from Person where name = Tiago
    System.out.println("------------------------------------------------------------------------");
    BasicDBObject basicObj = new BasicDBObject("name", "Tiago");
    cursor = collection.get(1).find(basicObj);
    while (cursor.hasNext()) {
        System.out.println(cursor.next());
    }

    //Select from Person where name = Tiago and surname = Carvalho
    System.out.println("------------------------------------------------------------------------");
    basicObj = new BasicDBObject("name", "Tiago").append("surname", "Carvalho");
    cursor = collection.get(1).find(basicObj);
    while (cursor.hasNext()) {
        System.out.println(cursor.next());
    }

    //Select * from Person where name = Tiago and surname = Erro
    System.out.println("------------------------------------------------------------------------");
    basicObj = new BasicDBObject("name", "Tiago").append("surname", "Erro");
    cursor = collection.get(1).find(basicObj);
    while (cursor.hasNext()) {
        System.out.println(cursor.next());
    }

    //SELECT * FROM PERSON WHERE surname like '%arval%'
    System.out.println("------------------------------------------------------------------------");
    basicObj = new BasicDBObject("surname", java.util.regex.Pattern.compile("arval"));
    cursor = collection.get(1).find(basicObj);
    while (cursor.hasNext()) {
        System.out.println(cursor.next());
    }
    //SELECT * FROM PERSON WHERE surname like '%arval%'
    System.out.println("------------------------------------------------------------------------");
    basicObj = new BasicDBObject();
    basicObj.put("surname", java.util.regex.Pattern.compile("arval"));
    cursor = collection.get(1).find(basicObj);
    while (cursor.hasNext()) {
        System.out.println(cursor.next());
    }
}

From source file:pt.tiago.mongodbteste.MongoDB.java

private void testReferences() {
    DBCursor cursor = collection.get(1).find();
    while (cursor.hasNext()) {
        DBObject obj = cursor.next();/* ww w . ja v a2s.  c o  m*/
        BasicDBObject basicObj = (BasicDBObject) obj;
        Person person = new Person();
        person.setID(String.valueOf(basicObj.getObjectId("_id")));
        person.setName(basicObj.getString("name"));
        person.setSurname(basicObj.getString("surname"));
        DBRef addressRef = new DBRef(db, "Person", basicObj.getObjectId("_id"));
        DBObject address = addressRef.fetch();
        BasicDBObject doc = new BasicDBObject().append("name", person.getName())
                .append("surname", person.getSurname()).append("pai", basicObj.getObjectId("_id"));
        collection.get(1).save(doc);
    }
}

From source file:rapture.sheet.mongodb.MongoCellStore.java

License:Open Source License

public List<RaptureSheetCell> findCellsByEpoch(final String sheetName, final int dimension,
        final long minEpochFilter) {

    MongoRetryWrapper<List<RaptureSheetCell>> wrapper = new MongoRetryWrapper<List<RaptureSheetCell>>() {

        public DBCursor makeCursor() {
            DBCollection collection = MongoDBFactory.getDB(instanceName).getCollection(tableName);
            BasicDBObject query = new BasicDBObject();
            query.put(KEY, sheetName);/*from   w  w w  .  ja  v  a  2s. c om*/
            query.put(DIM, dimension);
            return collection.find(query);
        }

        public List<RaptureSheetCell> action(DBCursor cursor) {
            List<RaptureSheetCell> ret = new ArrayList<RaptureSheetCell>();
            Long maxEpoch = 0L;

            while (cursor.hasNext()) {
                BasicDBObject val = (BasicDBObject) cursor.next();
                RaptureSheetCell cell = new RaptureSheetCell();
                cell.setColumn(val.getInt(COL));
                cell.setRow(val.getInt(ROW));
                cell.setData(val.getString(VALUE));
                boolean shouldAdd;
                if (val.containsField(EPOCH)) {
                    long currEpoch = val.getLong(EPOCH);
                    shouldAdd = (currEpoch > minEpochFilter);
                    cell.setEpoch(currEpoch);
                    if (maxEpoch < currEpoch) {
                        maxEpoch = currEpoch;
                    }
                } else {
                    shouldAdd = true;
                }

                if (shouldAdd)
                    ret.add(cell);
            }
            return ret;
        }
    };
    return wrapper.doAction();
}

From source file:rapture.sheet.mongodb.MongoMetaSheetStore.java

License:Open Source License

/**
 * Styles are stored with type=STYLE, and the content is a JSONed
 * RaptureSheetStyle//ww  w. jav  a2 s.co m
 *
 * @param name
 * @return
 */
public List<RaptureSheetStyle> getSheetStyles(final String name) {
    MongoRetryWrapper<List<RaptureSheetStyle>> wrapper = new MongoRetryWrapper<List<RaptureSheetStyle>>() {

        public DBCursor makeCursor() {
            DBCollection collection = MongoDBFactory.getDB(instanceName).getCollection(tableName);
            BasicDBObject query = new BasicDBObject();
            query.append(TYPE, STYLE);
            query.append(KEY, name);
            BasicDBObject values = new BasicDBObject();
            values.append(VALUE, 1);
            return collection.find(query, values);
        }

        public List<RaptureSheetStyle> action(DBCursor cursor) {
            List<RaptureSheetStyle> ret = new ArrayList<RaptureSheetStyle>();
            while (cursor.hasNext()) {
                BasicDBObject obj = (BasicDBObject) cursor.next();
                String content = obj.getString(VALUE);
                RaptureSheetStyle style = JacksonUtil.objectFromJson(content, RaptureSheetStyle.class);
                ret.add(style);
            }
            return ret;
        }
    };
    return wrapper.doAction();
}