Example usage for com.mongodb BasicDBList BasicDBList

List of usage examples for com.mongodb BasicDBList BasicDBList

Introduction

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

Prototype

BasicDBList

Source Link

Usage

From source file:org.apache.gora.mongodb.store.MongoStore.java

License:Apache License

/**
 * Convert a Java {@link GenericArray} as used in Gora generated classes to a
 * List that can safely be serialized into MongoDB.
 * //www .ja  va2 s. c  o  m
 * @param array
 *          the {@link GenericArray} to be serialized
 * @param fieldType
 *          type of the elements within the array
 * @return a {@link BasicDBList} version of the {@link GenericArray} that can
 *         be safely serialized into MongoDB.
 */
private BasicDBList listToMongo(final String docf, final Collection<?> array, final Schema fieldSchema,
        final Type fieldType) {
    BasicDBList list = new BasicDBList();
    // Handle null case
    if (array == null)
        return list;

    // Handle regular cases
    for (Object item : array) {
        DocumentFieldType storeType = mapping.getDocumentFieldType(docf);
        Object result = toDBObject(docf, fieldSchema, fieldType, storeType, item);
        list.add(result);
    }

    return list;
}

From source file:org.apache.karaf.jaas.modules.mongo.internal.DefaultUserDetailService.java

License:Apache License

@Override
public UserInfo addUser(UserInfo user) throws Exception {

    DB db = getDB();/*from  ww w.j  a v  a2 s  .  c  o m*/

    DBCollection users = db.getCollection(configuration.getUserCollectionName());

    DBCollection roles = db.getCollection(configuration.getGroupCollectionName());

    DBObject storedUser = users.findOne(new BasicDBObject().append("username", user.getName()));

    if (storedUser == null) {

        users.insert(BasicDBObjectBuilder.start("username", user.getName())
                .append("passwordHash", user.getPassword()).get());

    } else {
        // will not do anything here
    }

    for (String role : user.getGroups()) {

        DBObject roleQuery = new BasicDBObject("name", role);

        // roles are unique by name
        DBObject roleData = roles.findOne(roleQuery, ROLE_PROJECTION);

        if (roleData == null) {
            // add role with user as first member
            BasicDBList members = new BasicDBList();
            members.add(user.getName());
            roleData = BasicDBObjectBuilder.start().add("name", role).add("members", members).get();

            roles.insert(roleData);

        } else {

            // add user to group if not already in the role's member list
            Object mo = roleData.get("members");
            if (mo == null) {

                // TODO what here?
                BasicDBObject updateObject = new BasicDBObject().append("$push",
                        new BasicDBObject("members", user.getName()));

                roles.update(roleQuery, updateObject);

            } else if (mo != null && mo instanceof List) {

                // if user is in group already we dont need to do anything
                List<?> existingMembers = (List<?>) mo;

                if (!existingMembers.contains(user.getName())) {
                    // push this user to the members list
                    BasicDBObject updateObject = new BasicDBObject().append("$push",
                            new BasicDBObject("members", user.getName()));

                    roles.update(roleQuery, updateObject);

                }

            } else {
                log.warn("The members collection of group [{}] is not a list but of type [{}].", role,
                        mo.getClass().getName());
            }

        }

    }

    return user;
}

From source file:org.apache.logging.log4j.nosql.appender.mongodb.MongoDbObject.java

License:Apache License

@Override
public void set(final String field, final Object[] values) {
    final BasicDBList list = new BasicDBList();
    Collections.addAll(list, values);
    this.mongoObject.append(field, list);
}

From source file:org.apache.logging.log4j.nosql.appender.mongodb.MongoDbObject.java

License:Apache License

@Override
public void set(final String field, final NoSqlObject<BasicDBObject>[] values) {
    final BasicDBList list = new BasicDBList();
    for (final NoSqlObject<BasicDBObject> value : values) {
        list.add(value.unwrap());/*from  www  .ja  v  a  2 s . c o  m*/
    }
    this.mongoObject.append(field, list);
}

From source file:org.apache.metamodel.mongodb.mongo2.MongoDbDataContext.java

License:Apache License

private void convertToCursorObject(BasicDBObject query, FilterItem item) {
    if (item.isCompoundFilter()) {

        BasicDBList orList = new BasicDBList();

        final FilterItem[] childItems = item.getChildItems();
        for (FilterItem childItem : childItems) {
            BasicDBObject childObject = new BasicDBObject();
            convertToCursorObject(childObject, childItem);
            orList.add(childObject);//from   w w w.j  a  v a2 s . c  o m
        }

        query.put("$or", orList);

    } else {

        final Column column = item.getSelectItem().getColumn();
        final String columnName = column.getName();
        final String operatorName = getOperatorName(item);

        Object operand = item.getOperand();
        if (ObjectId.isValid(String.valueOf(operand))) {
            operand = new ObjectId(String.valueOf(operand));
        }

        final BasicDBObject existingFilterObject = (BasicDBObject) query.get(columnName);
        if (existingFilterObject == null) {
            if (operatorName == null) {
                if (OperatorType.LIKE.equals(item.getOperator())) {
                    query.put(columnName, turnOperandIntoRegExp(operand));
                } else {
                    query.put(columnName, operand);
                }
            } else {
                query.put(columnName, new BasicDBObject(operatorName, operand));
            }
        } else {
            if (operatorName == null) {
                throw new IllegalStateException(
                        "Cannot retrieve records for a column with two EQUALS_TO operators");
            } else {
                existingFilterObject.append(operatorName, operand);
            }
        }
    }
}

From source file:org.apache.metamodel.mongodb.MongoDbDataContext.java

License:Apache License

private void convertToCursorObject(BasicDBObject query, FilterItem item) {
    if (item.isCompoundFilter()) {

        BasicDBList orList = new BasicDBList();

        final FilterItem[] childItems = item.getChildItems();
        for (FilterItem childItem : childItems) {
            BasicDBObject childObject = new BasicDBObject();
            convertToCursorObject(childObject, childItem);
            orList.add(childObject);/*  w w w  . ja  v a  2  s . c  o m*/
        }

        query.put("$or", orList);

    } else {

        final Column column = item.getSelectItem().getColumn();
        final String columnName = column.getName();
        final Object operand = item.getOperand();
        final String operatorName = getOperatorName(item);

        final BasicDBObject existingFilterObject = (BasicDBObject) query.get(columnName);
        if (existingFilterObject == null) {
            if (operatorName == null) {
                if (OperatorType.LIKE.equals(item.getOperator())) {
                    query.put(columnName, turnOperandIntoRegExp(operand));
                } else {
                    query.put(columnName, operand);
                }
            } else {
                query.put(columnName, new BasicDBObject(operatorName, operand));
            }
        } else {
            if (operatorName == null) {
                throw new IllegalStateException(
                        "Cannot retrieve records for a column with two EQUALS_TO operators");
            } else {
                existingFilterObject.append(operatorName, operand);
            }
        }
    }
}

From source file:org.atlasapi.persistence.content.mongo.MongoDBQueryBuilder.java

License:Apache License

private List<ConstrainedAttribute> buildQueries(ContentQuery query) {
    return query.accept(new QueryVisitor<ConstrainedAttribute>() {

        @Override/*from   w w  w. j  a  v a  2 s  .  c om*/
        @SuppressWarnings("unchecked")
        public ConstrainedAttribute visit(IntegerAttributeQuery query) {
            final List<Integer> values = (List<Integer>) query.getValue();

            BasicDBObject rhs = query.accept(new IntegerOperatorVisitor<BasicDBObject>() {

                @Override
                public BasicDBObject visit(Equals equals) {
                    return new BasicDBObject(IN, list(values));
                }

                @Override
                public BasicDBObject visit(LessThan lessThan) {
                    return new BasicDBObject(LESS_THAN, Collections.max(values));
                }

                @Override
                public BasicDBObject visit(GreaterThan greaterThan) {
                    return new BasicDBObject(GREATER_THAN, Collections.min(values));
                }
            });

            return new ConstrainedAttribute(query.getAttribute(), rhs);
        }

        @Override
        public ConstrainedAttribute visit(final StringAttributeQuery query) {
            final BasicDBList values = new BasicDBList();
            values.addAll(query.getValue());

            return query.accept(new StringOperatorVisitor<ConstrainedAttribute>() {

                @Override
                public ConstrainedAttribute visit(Equals equals) {
                    return new ConstrainedAttribute(query.getAttribute(), new BasicDBObject(IN, values));
                }

                @Override
                public ConstrainedAttribute visit(Beginning beginning) {
                    Pattern pattern = Pattern.compile("^" + (String) query.getValue().get(0),
                            Pattern.CASE_INSENSITIVE);
                    return new ConstrainedAttribute(query.getAttribute(), pattern);
                }
            });

        }

        @Override
        public ConstrainedAttribute visit(final BooleanAttributeQuery query) {

            if (query.isUnconditionallyTrue()) {
                return null;
            }

            final Boolean value = (Boolean) query.getValue().get(0);

            return query.accept(new BooleanOperatorVisitor<ConstrainedAttribute>() {

                @Override
                public ConstrainedAttribute visit(Equals equals) {
                    return new ConstrainedAttribute(query.getAttribute(), value);
                }
            });

        }

        @Override
        @SuppressWarnings("unchecked")
        public ConstrainedAttribute visit(final EnumAttributeQuery<?> query) {

            final List<Enum<?>> values = (List<Enum<?>>) query.getValue();

            return query.accept(new EnumOperatorVisitor<ConstrainedAttribute>() {

                @Override
                public ConstrainedAttribute visit(Equals equals) {
                    return new ConstrainedAttribute(query.getAttribute(),
                            new BasicDBObject(IN, list(toLowercaseStrings(values))));
                }

                private Collection<?> toLowercaseStrings(Collection<Enum<?>> values) {
                    List<String> strings = Lists.newArrayList();
                    for (Enum<?> value : values) {
                        strings.add(value.toString().toLowerCase());
                    }
                    return strings;
                }
            });
        }

        @SuppressWarnings("unchecked")
        @Override
        public ConstrainedAttribute visit(DateTimeAttributeQuery query) {
            final List<Date> values = toDate((List<DateTime>) query.getValue());

            BasicDBObject rhs = query.accept(new DateTimeOperatorVisitor<BasicDBObject>() {

                @Override
                public BasicDBObject visit(Before before) {
                    return new BasicDBObject(LESS_THAN, Collections.max(values));
                }

                @Override
                public BasicDBObject visit(After after) {
                    return new BasicDBObject(GREATER_THAN, Collections.min(values));
                }

                @Override
                public BasicDBObject visit(Equals equals) {
                    throw new UnsupportedOperationException();
                }
            });
            return new ConstrainedAttribute(query.getAttribute(), rhs);
        }

        private List<Date> toDate(List<DateTime> values) {
            return Lists.transform(values, new Function<DateTime, Date>() {
                @Override
                public Date apply(DateTime time) {
                    return time.toDateTime(DateTimeZones.UTC).toDate();
                }
            });
        }

        @Override
        public ConstrainedAttribute visit(MatchesNothing noOp) {
            throw new IllegalArgumentException();
        }
    });
}

From source file:org.atlasapi.persistence.content.mongo.MongoDBQueryBuilder.java

License:Apache License

private static BasicDBList list(Collection<?> elems) {
    final BasicDBList list = new BasicDBList();
    list.addAll(elems);//from w  w w  .  ja  v a  2  s.  co  m
    return list;
}

From source file:org.aw20.mongoworkbench.command.MapReduceMongoCommand.java

License:Open Source License

@SuppressWarnings("deprecation")
@Override// w  w w  .j a  v  a2 s.c  om
public void execute() throws Exception {
    MongoClient mdb = MongoFactory.getInst().getMongo(sName);

    if (mdb == null)
        throw new Exception("no server selected");

    if (sDb == null)
        throw new Exception("no database selected");

    MongoFactory.getInst().setActiveDB(sDb);

    DB db = mdb.getDB(sDb);
    BasicDBObject cmdMap = parseMongoCommandString(db, cmd);

    if (!cmdMap.containsField("mapreduceArgs"))
        throw new Exception("no mapReduce document");

    DBCollection collection = db.getCollection(sColl);

    // Build the Map
    BasicDBObject options = (BasicDBObject) ((BasicDBList) cmdMap.get("mapreduceArgs")).get(2);

    String outputCollection = null;
    String outputDB = null;
    MapReduceCommand.OutputType outputType = MapReduceCommand.OutputType.INLINE;

    if (options.get("out") instanceof String) {
        outputCollection = (String) options.get("out");
        outputType = MapReduceCommand.OutputType.REPLACE;
    } else if (options.get("out") instanceof BasicDBObject) {
        BasicDBObject out = (BasicDBObject) options.get("out");

        if (out.containsField("inline")) {
            outputCollection = null;
        } else if (out.containsField("replace")) {
            outputCollection = (String) out.get("replace");
            outputType = MapReduceCommand.OutputType.REPLACE;
        } else if (out.containsField("merge")) {
            outputCollection = (String) out.get("merge");
            outputType = MapReduceCommand.OutputType.MERGE;
        } else if (out.containsField("reduce")) {
            outputCollection = (String) out.get("reduce");
            outputType = MapReduceCommand.OutputType.REDUCE;
        }

        if (out.containsField("db"))
            outputDB = (String) out.get("db");
    }

    MapReduceCommand mrc = new MapReduceCommand(collection,
            ((Code) ((BasicDBList) cmdMap.get("mapreduceArgs")).get(0)).getCode(),
            ((Code) ((BasicDBList) cmdMap.get("mapreduceArgs")).get(1)).getCode(), outputCollection, outputType,
            (BasicDBObject) options.get("query"));

    if (outputDB != null)
        mrc.setOutputDB(outputDB);

    if (options.containsField("sort") && options.get("sort") instanceof DBObject)
        mrc.setSort((DBObject) options.get("sort"));

    if (options.containsField("scope") && options.get("scope") instanceof DBObject)
        mrc.setScope(((DBObject) options.get("scope")).toMap());

    if (options.containsField("finalize") && options.get("scope") instanceof Code)
        mrc.setFinalize(((Code) options.get("scope")).getCode());

    if (options.containsField("limit"))
        mrc.setLimit(StringUtil.toInteger(options.get("limit"), -1));

    mrc.addExtraOption("jsMode", StringUtil.toBoolean(options.get("jsMode"), false));
    mrc.setVerbose(StringUtil.toBoolean(options.get("verbose"), false));

    // Run the actual mapreduce function
    MapReduceOutput mro = collection.mapReduce(mrc);

    // Pull the inline results
    if (mro.getOutputCollection() == null) {
        dbListResult = new BasicDBList();
        Iterable<DBObject> it = mro.results();
        for (DBObject dbo : it) {
            dbListResult.add(dbo);
        }
    }

    BasicDBObject dbo = mro.getRaw();
    StringBuilder sb = new StringBuilder();

    if (dbo.containsField("timeMillis"))
        sb.append("Time=").append(dbo.get("timeMillis")).append("ms; ");

    if (dbo.containsField("counts")) {
        BasicDBObject counts = (BasicDBObject) dbo.get("counts");
        sb.append("Counts: input=" + counts.get("input"));
        sb.append("; emit=" + counts.get("emit"));
        sb.append("; reduce=" + counts.get("reduce"));
        sb.append("; output=" + counts.get("output"));
    }

    setMessage(sb.toString());
}

From source file:org.axonframework.eventhandling.saga.repository.mongo.SagaEntry.java

License:Apache License

private static List toDBList(Iterable<AssociationValue> associationValues) {
    BasicDBList list = new BasicDBList();
    for (AssociationValue associationValue : associationValues) {
        list.add(new BasicDBObject(ASSOCIATION_KEY, associationValue.getKey()).append(ASSOCIATION_VALUE,
                associationValue.getValue()));
    }/*from  ww w . j  a  va 2  s.  c  o m*/
    return list;
}