Example usage for com.mongodb BasicDBObject containsField

List of usage examples for com.mongodb BasicDBObject containsField

Introduction

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

Prototype

public boolean containsField(final String field) 

Source Link

Document

Checks if this object contains a given field

Usage

From source file:org.benjp.server.ChatServer.java

License:Open Source License

@Resource
@Route("/getMeetingNotes")
public Response.Content getMeetingNotes(String user, String token, String room, String fromTimestamp,
        String toTimestamp, String serverBase) throws IOException {
    if (!tokenService.hasUserWithToken(user, token)) {
        return Response.notFound("Petit malin !");
    }//from   w  w w .  j a v a 2 s  .co  m

    Long from = null;
    Long to = null;
    String xwiki = "";
    try {
        if (fromTimestamp != null && !"".equals(fromTimestamp))
            from = Long.parseLong(fromTimestamp);
    } catch (NumberFormatException nfe) {
        log.info("fromTimestamp is not a valid Long number");
    }
    try {
        if (toTimestamp != null && !"".equals(toTimestamp))
            to = Long.parseLong(toTimestamp);
    } catch (NumberFormatException nfe) {
        log.info("fromTimestamp is not a valid Long number");
    }
    String data = chatService.read(room, userService, false, from, to);
    BasicDBObject datao = (BasicDBObject) JSON.parse(data);
    if (datao.containsField("messages")) {
        List<UserBean> users = userService.getUsers(room);
        ReportBean reportBean = new ReportBean();
        reportBean.fill((BasicDBList) datao.get("messages"), users);

        String roomName = "";
        List<SpaceBean> spaces = userService.getSpaces(user);
        for (SpaceBean spaceBean : spaces) {
            if (room.equals(spaceBean.getRoom())) {
                roomName = spaceBean.getDisplayName();
            }
        }
        List<RoomBean> roomBeans = userService.getTeams(user);
        for (RoomBean roomBean : roomBeans) {
            if (room.equals(roomBean.getRoom())) {
                roomName = roomBean.getFullname();
            }
        }
        xwiki = reportBean.getAsXWiki(serverBase);

    }

    return Response.ok(xwiki).withMimeType("text/event-stream; charset=UTF-8").withHeader("Cache-Control",
            "no-cache");
}

From source file:org.eclipse.birt.data.oda.mongodb.internal.impl.QueryModel.java

License:Open Source License

private static void validateAggregateCommand(DBObject commandObj) throws OdaException {
    // validate a $group pipeline operation expression, if specified
    List<BasicDBObject> groupOps = findPipelineOperation(commandObj, GROUP_AGGR_KEY);
    for (BasicDBObject groupOp : groupOps) {
        if (!groupOp.containsField(DOC_ID_FIELD_NAME))
            throw new OdaException(Messages.bind(Messages.queryModel_missingGroupAggrKey,
                    new Object[] { GROUP_AGGR_KEY, DOC_ID_FIELD_NAME, groupOp }));
    }/*from   ww  w .  j a va  2s.  c om*/

    // validate a $sort pipeline operation expression, if specified
    List<BasicDBObject> sortOps = findPipelineOperation(commandObj, SORT_AGGR_KEY);
    for (BasicDBObject sortOp : sortOps) {
        for (Object sortKeySpec : sortOp.values()) {
            if (sortKeySpec instanceof Number) {
                int sortKeyValue = ((Number) sortKeySpec).intValue();
                if (sortKeyValue == 1 || sortKeyValue == -1)
                    continue; // is valid
            }
            throw new OdaException(
                    Messages.bind(Messages.queryModel_invalidSortAggrValue, SORT_AGGR_KEY, sortOp));
        }
    }
}

From source file:org.eclipse.birt.data.oda.mongodb.internal.impl.QueryProperties.java

License:Open Source License

DBObject getSelectedFieldsAsProjectionKeys() throws OdaException {
    Object propValue = getPropertiesMap().get(SELECTED_FIELDS_PROP);
    if (propValue instanceof List<?>) {
        BasicDBObject keys = new BasicDBObject();
        @SuppressWarnings("unchecked")
        List<String> fieldNames = (List<String>) propValue;
        for (String field : fieldNames) {
            keys.append(field, 1);//from  w  w w  .  j  av  a2s. c  o m
        }

        // explicitly exclude docId field if not in projected list
        if (!keys.containsField(DOC_ID_FIELD_NAME))
            keys.append(DOC_ID_FIELD_NAME, 0);
        return keys;
    }

    if (propValue instanceof String) {
        // user-defined projection expression
        return parseExprToDBObject((String) propValue);
    }

    // non-recognized data type; log and ignore
    if (propValue != null)
        getLogger().log(Level.INFO,
                Messages.bind("Unexpected data type ({0}) in Selected Fields property value.", //$NON-NLS-1$
                        propValue.getClass().getName()));

    return new BasicDBObject();
}

From source file:org.exoplatform.chat.server.ChatServer.java

License:Open Source License

@Resource
@Route("/sendMeetingNotes")
public Response.Content sendMeetingNotes(String user, String token, String room, String fromTimestamp,
        String toTimestamp) throws IOException {
    if (!tokenService.hasUserWithToken(user, token)) {
        return Response.notFound("Petit malin !");
    }//w w w  .  ja v a2s  .  co  m

    Long from = null;
    Long to = null;
    String html = "";
    try {
        if (fromTimestamp != null && !"".equals(fromTimestamp))
            from = Long.parseLong(fromTimestamp);
    } catch (NumberFormatException nfe) {
        LOG.info("fromTimestamp is not a valid Long number");
    }
    try {
        if (toTimestamp != null && !"".equals(toTimestamp))
            to = Long.parseLong(toTimestamp);
    } catch (NumberFormatException nfe) {
        LOG.info("fromTimestamp is not a valid Long number");
    }
    String data = chatService.read(room, userService, false, from, to);
    BasicDBObject datao = (BasicDBObject) JSON.parse(data);
    if (datao.containsField("messages")) {
        List<UserBean> users = userService.getUsers(room);
        ReportBean reportBean = new ReportBean();
        reportBean.fill((BasicDBList) datao.get("messages"), users);

        ArrayList<String> tos = new ArrayList<String>();
        String senderFullname = user;
        for (UserBean userBean : users) {
            if (!"".equals(userBean.getEmail())) {
                tos.add(userBean.getEmail());
            }
            if (user.equals(userBean.getName())) {
                senderFullname = userBean.getFullname();
            }
        }

        String roomName = "";
        List<SpaceBean> spaces = userService.getSpaces(user);
        for (SpaceBean spaceBean : spaces) {
            if (room.equals(spaceBean.getRoom())) {
                roomName = spaceBean.getDisplayName();
            }
        }
        List<RoomBean> roomBeans = userService.getTeams(user);
        for (RoomBean roomBean : roomBeans) {
            if (room.equals(roomBean.getRoom())) {
                roomName = roomBean.getFullname();
            }
        }
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
        String date = formatter.format(new GregorianCalendar().getTime());
        String title = roomName + " : Meeting Notes [" + date + "]";
        html = reportBean.getAsHtml(title);

        try {
            sendMailWithAuth(senderFullname, tos, html.toString(), title);
        } catch (Exception e) {
            LOG.info(e.getMessage());
        }

    }

    return Response.ok("sent").withMimeType("text/event-stream; charset=UTF-8").withHeader("Cache-Control",
            "no-cache");
}

From source file:org.exoplatform.chat.server.ChatServer.java

License:Open Source License

@Resource
@Route("/getMeetingNotes")
public Response.Content getMeetingNotes(String user, String token, String room, String fromTimestamp,
        String toTimestamp, String serverBase) throws IOException {
    if (!tokenService.hasUserWithToken(user, token)) {
        return Response.notFound("Petit malin !");
    }/*from   www.j  a v  a2s .  c om*/

    Long from = null;
    Long to = null;
    String xwiki = "";
    try {
        if (fromTimestamp != null && !"".equals(fromTimestamp))
            from = Long.parseLong(fromTimestamp);
    } catch (NumberFormatException nfe) {
        LOG.info("fromTimestamp is not a valid Long number");
    }
    try {
        if (toTimestamp != null && !"".equals(toTimestamp))
            to = Long.parseLong(toTimestamp);
    } catch (NumberFormatException nfe) {
        LOG.info("fromTimestamp is not a valid Long number");
    }
    String data = chatService.read(room, userService, false, from, to);
    BasicDBObject datao = (BasicDBObject) JSON.parse(data);
    if (datao.containsField("messages")) {
        List<UserBean> users = userService.getUsers(room);
        ReportBean reportBean = new ReportBean();
        reportBean.fill((BasicDBList) datao.get("messages"), users);

        String roomName = "";
        List<SpaceBean> spaces = userService.getSpaces(user);
        for (SpaceBean spaceBean : spaces) {
            if (room.equals(spaceBean.getRoom())) {
                roomName = spaceBean.getDisplayName();
            }
        }
        List<RoomBean> roomBeans = userService.getTeams(user);
        for (RoomBean roomBean : roomBeans) {
            if (room.equals(roomBean.getRoom())) {
                roomName = roomBean.getFullname();
            }
        }
        xwiki = reportBean.getAsXWiki(serverBase);

    }

    return Response.ok(xwiki).withMimeType("text/event-stream; charset=UTF-8").withHeader("Cache-Control",
            "no-cache");
}

From source file:org.opengrid.data.impl.PlenarioDataProvider.java

private String getGeoFilter(String options) throws ParseException, UnsupportedEncodingException {
    String geoType = "Polygon";
    // String geoCoordinates =
    // properties.getStringProperty("plenario.geo.default");

    String geoCoordinates = properties.getStringProperty("plenario.geo.default");

    if (options != null && options.length() > 0) {
        BasicDBObject o = (BasicDBObject) JSON.parse(options);

        if (o.containsField("geoFilter")) {
            BasicDBObject qo = (BasicDBObject) o.get("geoFilter");

            geoType = (String) qo.get("type");

            BasicDBList coordinatesList = (BasicDBList) qo.get("coordinates");

            geoCoordinates = coordinatesList.toString().replace(" ", "%20");

        }/*w ww.j  av  a 2 s  . c  om*/
    }

    return "&location_geom__within={\"type\":\"Feature\",\"properties\":{},\"geometry\":{\"type\":\"" + geoType
            + "\",\"coordinates\":" + geoCoordinates + "}}";
}

From source file:org.restheart.handlers.bulk.BulkPostCollectionHandler.java

License:Open Source License

private boolean checkId(HttpServerExchange exchange, RequestContext context, BasicDBObject document) {
    if (document.get("_id") != null && document.get("_id") instanceof String
            && RequestContext.isReservedResourceDocument(context.getType(), (String) document.get("_id"))) {
        ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_FORBIDDEN,
                "id is reserved: " + document.get("_id"));
        return false;
    }/*from  w  w  w.j a  v  a  2  s .  c  o m*/

    if (document.containsField("_id")) {
        if (!(context.getDocIdType() == DOC_ID_TYPE.OID || context.getDocIdType() == DOC_ID_TYPE.STRING_OID)) {
            ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_NOT_ACCEPTABLE,
                    "_id in content body is mandatory for documents with id type "
                            + context.getDocIdType().name());
            return false;
        }
    }

    return true;
}

From source file:org.sdsai.dsds.mongo.MongoUtils.java

License:Open Source License

public static Object getPrimitive(final BasicDBObject dbo, final String fieldName, final Class<?> returnType)
        throws Exception {
    final boolean contained = dbo.containsField(fieldName);

    if (Boolean.TYPE.equals(returnType))
        return contained ? dbo.getBoolean(fieldName) : Boolean.FALSE;

    if (Short.TYPE.equals(returnType) || Byte.TYPE.equals(returnType) || Integer.TYPE.equals(returnType))
        return (Integer) (contained ? dbo.getInt(fieldName) : 0);

    if (Character.TYPE.equals(returnType))
        return (Character) ((dbo.get(fieldName) + "").charAt(0));

    if (Long.TYPE.equals(returnType))
        return (Long) (contained ? dbo.getLong(fieldName) : 0L);

    if (Float.TYPE.equals(returnType))
        return (Float) (contained ? Float.valueOf(dbo.get(fieldName) + "") : 0F);

    if (Double.TYPE.equals(returnType))
        return (Double) (contained ? dbo.getDouble(fieldName) : 0D);

    return null;//from   ww w  . j  av a 2 s. com
}

From source file:org.sipfoundry.sipxconfig.mongo.MongoServer.java

License:Open Source License

public MongoServer(BasicDBObject dbo) {
    m_id = dbo.getInt("_id");
    m_name = dbo.getString("name");
    m_type = SERVER;//from  w  w  w.ja  v  a  2s. c o m
    if (StringUtils.contains(m_name, String.valueOf(MongoSettings.ARBITER_PORT))) {
        m_type = ARBITER;
    }
    m_configured = true;
    m_state = dbo.getString("stateStr");
    m_health = UP;
    if (dbo.containsField(HEALTH)) {
        if (dbo.getInt(HEALTH) == 0) {
            m_health = DOWN;
        }
    }
    if (dbo.containsField(ERR_MSG)) {
        m_errMsg = dbo.getString(ERR_MSG);
    }
    try {
        BSONTimestamp optime = (BSONTimestamp) dbo.get("optime");
        if (optime.getTime() != 0) {
            m_optimeDate = new Date((long) optime.getTime() * 1000).toString();
        }
    } catch (NumberFormatException ex) {
        m_optimeDate = NA;
    }
}

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

License:Open Source License

public ObjectStoreResponse updateObject(ObjectRequest objectRequest) {

    try {//  w w w .j  av  a 2s.  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;
    }
}