Example usage for com.mongodb BasicDBObject toString

List of usage examples for com.mongodb BasicDBObject toString

Introduction

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

Prototype

@SuppressWarnings("deprecation")
public String toString() 

Source Link

Document

Returns a JSON serialization of this object

The output will look like: {"a":1, "b":["x","y","z"]} }

Usage

From source file:eu.operando.core.udb.UserAccountMongo.java

/**
 * Search the collection of users with a given json fileter and return
 * a JSON list of the results./*from w ww .j a  v a 2  s. co m*/
 * @param filter the query in json format.
 * @return A list of json objects that match the query. This is a single json document of this result.
 */
public String getUserByFilter(String filter) {
    String result = null;
    BasicDBObject query = new BasicDBObject();

    System.out.println("filter expression: " + filter);

    try {
        JSONObject obj = new JSONObject(filter);
        Iterator<String> keys = obj.keys();
        while (keys.hasNext()) {
            String key = keys.next();
            query.put(key, java.util.regex.Pattern.compile(obj.getString(key)));
        }
    } catch (JSONException e) {
        return null;
    }

    System.out.println("Query: " + query.toString());

    List<UserAccount> arrUPPObj = new ArrayList<>();

    DBCursor cursor = this.userTable.find(query);
    boolean found = false;
    while (cursor.hasNext()) {
        BasicDBObject regObj = (BasicDBObject) cursor.next();
        arrUPPObj.add(getUser(regObj));
        found = true;
    }

    if (!found) {
        return null;
    }

    try {
        ObjectMapper mapper = new ObjectMapper();
        mapper.getSerializationConfig().enable(SerializationConfig.Feature.WRITE_ENUMS_USING_TO_STRING);
        mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);

        result = mapper.writeValueAsString(arrUPPObj);
    } catch (JsonMappingException e) {
        result = null;
    } catch (IOException e) {
        result = null;
    }

    System.out.println("getUPPByFilter RESULT (list): " + result);

    return result;
}

From source file:example.springdata.mongodb.util.MongosSystemForTestFactory.java

License:Apache License

private boolean isReplicaSetStarted(BasicDBObject setting) {
    if (setting.get("members") == null) {
        return false;
    }/*from  w w w  .j av  a  2s.  co m*/

    BasicDBList members = (BasicDBList) setting.get("members");
    for (Object m : members.toArray()) {
        BasicDBObject member = (BasicDBObject) m;
        logger.info(member.toString());
        int state = member.getInt("state");
        logger.info("state: {}", state);
        // 1 - PRIMARY, 2 - SECONDARY, 7 - ARBITER
        if (state != 1 && state != 2 && state != 7) {
            return false;
        }
    }
    return true;
}

From source file:fr.cnes.sitools.dataset.database.mongodb.RequestMongoDB.java

License:Open Source License

@Override
public String getAttributes(List<Column> columnVisible) {
    BasicDBObject keys = new BasicDBObject();
    boolean foundId = false;
    for (Column column : columnVisible) {
        if (ID_COLUMN_NAME.equals(column.getDataIndex())) {
            foundId = true;//from  ww w.  jav a2 s.  co m
        }
        keys.append(column.getDataIndex(), 1);
    }
    if (!foundId) {
        keys.append(ID_COLUMN_NAME, 0);
    }

    return keys.toString();
}

From source file:fr.cnes.sitools.dataset.database.mongodb.RequestMongoDB.java

License:Open Source License

@Override
public String getFilterClause(List<Predicat> predicats, List<Column> columns) {
    BasicDBObject whereClause = new BasicDBObject();
    // loop over the predicats
    // boolean first = true;
    // String result = "{";
    ////from w  ww . ja v a2 s .co m
    // Map<String, List<Predicat>> orderedPredicats = orderPredicat(predicats);
    // for (Predicat predicat : predicats) {
    //
    // String filter = getFilter(predicat);
    // if (filter != null && !"".equals(filter)) {
    // // DBObject objPredicat = (DBObject) JSON.parse(filter);
    // // if (objPredicat != null) {
    // if (first) {
    // whereClause.append("$and", new ArrayList<DBObject>());
    // }
    // else {
    // result += ",";
    // }
    // first = false;
    //
    // result += filter;
    //
    // // ((List<DBObject>) whereClause.get("$and")).add(objPredicat);
    //
    // // if (whereClause.containsField(key)) {
    // // // If the key already exists append the value to the existing key
    // // // DBObject obj = new BasicDBObject();
    // // // obj.put("$and", objPredicat.get(key));
    // //
    // // if (!whereClause.containsField("$and")) {
    // // whereClause.append("$and", new ArrayList<DBObject>());
    // // DBObject pred = (DBObject) whereClause.get(key);
    // // whereClause.remove(key);
    // // ((List<DBObject>) whereClause.get("$and")).add(pred);
    // //
    // // }
    // // ((List<DBObject>) whereClause.get("$and")).add(objPredicat);
    // //
    // // // ((DBObject) whereClause.get(key)).putAll(obj);
    // // }
    // // else {
    // // // if the key doesn't exists just append the predicat to the whereClause
    // // whereClause.append(key, objPredicat.get(key));
    // // }
    //
    // }
    // // }
    // }

    for (Predicat predicat : predicats) {
        String filter = getFilter(predicat);
        if (filter != null && !"".equals(filter)) {
            DBObject objPredicat = (DBObject) JSON.parse(filter);
            if (objPredicat != null) {
                Set<String> keys = objPredicat.keySet();
                for (String key : keys) {
                    if (whereClause.containsField(key)) {
                        ((DBObject) whereClause.get(key)).putAll((DBObject) objPredicat.get(key));
                    } else {
                        whereClause.append(key, objPredicat.get(key));
                    }

                }
            }
        }
    }

    return whereClause.toString();
}

From source file:fr.cnes.sitools.dataset.database.mongodb.RequestMongoDB.java

License:Open Source License

@Override
public String getFilter(Predicat predicat) {
    String jsonPredicat = "";
    if (predicat.getStringDefinition() != null && !"".equals(predicat.getStringDefinition())) {
        return predicat.getStringDefinition();
    }//  w  w w. j a  v  a 2 s .  com
    BasicDBObject object = null;
    Object value = null;

    if (predicat.getRightValue() != null) {
        // filtre
        if (predicat.getRightValue() instanceof String) {
            // rightValue = ((String) predicat.getRightValue()).replace("'", "");
            value = getValueFromColumnType(predicat.getRightValue(), predicat);

        } else if (predicat.getRightValue() instanceof Boolean) {
            value = predicat.getRightValue();
        } else if (predicat.getRightValue() instanceof Double) {
            value = predicat.getRightValue();
        } else if (predicat.getRightValue() instanceof Float) {
            value = predicat.getRightValue();
        } else if (predicat.getRightValue() instanceof BigDecimal) {
            value = ((BigDecimal) predicat.getRightValue()).doubleValue();
        }
        // List of values
        else if (predicat.getRightValue() instanceof List) {
            @SuppressWarnings("unchecked")
            List<String> values = (List<String>) predicat.getRightValue();
            List<Object> tmpValue = new ArrayList<Object>();
            for (String val : values) {
                tmpValue.add(getValueFromColumnType(val, predicat));
            }
            value = tmpValue;
        }
        // Geometry object
        else if (predicat.getRightValue() instanceof GeometryObject) {
            GeometryObject geom = (GeometryObject) predicat.getRightValue();
            List<List<Double>> points = new ArrayList<List<Double>>();
            for (Point point : geom.getPoints()) {
                List<Double> pointArray = new ArrayList<Double>();
                pointArray.add(point.getX());
                pointArray.add(point.getY());
                points.add(pointArray);
            }
            value = new BasicDBObject("$polygon", points);
        } else {
            value = predicat.getRightValue();
        }

        // get the compare operator and create a DBObject if it needs it
        String operator = OperatorMongoDB.getOperatorValue(predicat.getCompareOperator());
        if (Operator.LIKE.equals(predicat.getCompareOperator())) {
            value = Pattern.compile((String) value, Pattern.CASE_INSENSITIVE);
        } else if (operator != null) {
            value = new BasicDBObject(operator, value);
        }
        if (predicat.getLeftString() != null) {
            object = new BasicDBObject(predicat.getLeftString(), value);

        } else {
            object = new BasicDBObject(predicat.getLeftAttribute().getDataIndex(), value);
        }

    }

    if (object != null) {
        jsonPredicat = object.toString();
    }

    return jsonPredicat;
}

From source file:fr.cnes.sitools.dataset.database.mongodb.RequestMongoDB.java

License:Open Source License

@Override
public String getOrderBy(DataSet ds) {
    BasicDBObject orderBy = new BasicDBObject();
    List<Column> columnsOrderBy = ds.getColumnOrderBy();
    if (columnsOrderBy != null && columnsOrderBy.size() != 0) {
        for (Column column : columnsOrderBy) {
            int orderDir;
            if ("ASC".equals(column.getOrderBy())) {
                orderDir = 1;/*from  w  w  w  .ja  v  a2s  .  co m*/
            } else {
                orderDir = -1;
            }
            orderBy.append(column.getDataIndex(), orderDir);
        }
    }
    return orderBy.toString();
}

From source file:fr.cnes.sitools.dataset.database.mongodb.RequestMongoDB.java

License:Open Source License

/**
 * Get the Sorting Order for the given {@link Multisort} as a String
 * /*from  www  .j  a va 2 s .  c  o  m*/
 * @param multisort
 *          the sort order definition
 * @return the Sorting order as a String
 */
public String getOrderBy(Multisort multisort) {
    BasicDBObject orderBy = new BasicDBObject();
    Sort[] sorts = multisort.getOrdersList();
    if (sorts != null && sorts.length != 0) {
        for (int i = 0; i < sorts.length; i++) {
            Sort sort = sorts[i];
            int orderDir;
            if (SortOrder.ASC.equals(sort.getDirection())) {
                orderDir = 1;
            } else {
                orderDir = -1;
            }
            orderBy.append(sort.getField(), orderDir);
        }

    }
    return orderBy.toString();
}

From source file:fr.cnes.sitools.datasource.mongodb.business.MongoDBExplorerRepresentation.java

License:Open Source License

@Override
public void write(OutputStream outputStream) throws IOException {
    PrintStream out = new PrintStream(outputStream);
    out.println("{\"success\": true,");
    out.println("\"total\":" + cursor.count() + ",");

    out.println("\"data\":[");
    boolean first = true;
    while (cursor.hasNext()) {
        if (!first) {
            out.println(",");
        } else {//w  ww  .  ja  va  2s  .co  m
            first = false;
        }
        BasicDBObject record = (BasicDBObject) cursor.next();
        out.print(record.toString());
        out.flush();
    }

    out.println("],");

    out.println("\"count\":" + cursor.size() + ",");
    out.println("\"offset\":" + mongoDbResource.getStart());
    out.println("}");
    out.close();
}

From source file:fr.eolya.utils.nosql.mongodb.MongoDBCollection.java

License:Apache License

public String getJson(BasicDBObject docsearch) {
    BasicDBObject doc = get(docsearch);
    if (doc == null)
        return null;
    return (String) doc.toString();
}

From source file:fr.gouv.vitam.cases.ElasticSearchAccess.java

License:Open Source License

/**
 * /*from   w ww. j av a 2  s .c o m*/
 * @param dbvitam
 * @param model
 * @param bson
 * @return True if inserted in ES
 */
public static final boolean addEsIndex(final CassandraAccess dbvitam, final String model,
        final BSONObject bson) {
    BasicDBObject maip = getFiltered(bson);
    final String id = maip.getString(VitamType.ID);
    maip.removeField(VitamType.ID);
    return dbvitam.addEsEntryIndex(model, id, maip.toString());
}