Example usage for com.mongodb DBCollection update

List of usage examples for com.mongodb DBCollection update

Introduction

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

Prototype

public WriteResult update(final DBObject query, final DBObject update) 

Source Link

Document

Modify an existing document.

Usage

From source file:org.keycloak.connections.mongo.updater.impl.updates.AbstractMigrateUserFedToComponent.java

License:Apache License

public void portUserFedMappersToComponent(String providerId, String mapperType) {
    //logger.info("*** port mappers");
    DBCollection realms = db.getCollection("realms");
    DBCursor cursor = realms.find();/*from  www . j a  v a2 s . com*/
    while (cursor.hasNext()) {
        BasicDBObject realm = (BasicDBObject) cursor.next();

        String realmId = realm.getString("_id");
        Set<String> removedProviders = new HashSet<>();

        BasicDBList componentEntities = (BasicDBList) realm.get("componentEntities");
        BasicDBList federationProviders = (BasicDBList) realm.get("userFederationProviders");
        BasicDBList fedMappers = (BasicDBList) realm.get("userFederationMappers");
        for (Object obj : federationProviders) {
            BasicDBObject fedProvider = (BasicDBObject) obj;
            String providerName = fedProvider.getString("providerName");
            //logger.info("looking for mappers of fed provider: " + providerName);
            if (providerName.equals(providerId)) {
                String id = fedProvider.getString("id");
                //logger.info("found fed provider: " + id + ", looking at mappers");
                for (Object obj2 : fedMappers) {
                    BasicDBObject fedMapper = (BasicDBObject) obj2;
                    String federationProviderId = fedMapper.getString("federationProviderId");
                    //logger.info("looking at mapper with federationProviderId: " + federationProviderId);
                    if (federationProviderId.equals(id)) {
                        String name = fedMapper.getString("name");
                        String mapperId = fedMapper.getString("id");
                        removedProviders.add(mapperId);
                        String mapperProviderId = fedMapper.getString("federationMapperType");
                        BasicDBObject component = new BasicDBObject();
                        component.put("id", mapperId);
                        component.put("name", name);
                        component.put("providerType", mapperType);
                        component.put("providerId", mapperProviderId);
                        component.put("parentId", id);

                        BasicDBObject fedConfig = (BasicDBObject) fedMapper.get("config");
                        BasicDBObject config = new BasicDBObject();
                        if (fedConfig != null) {
                            for (Map.Entry<String, Object> attr : new HashSet<>(fedConfig.entrySet())) {
                                String attrName = attr.getKey();
                                String attrValue = attr.getValue().toString();
                                config.put(attrName, Collections.singletonList(attrValue));

                            }
                        }
                        component.put("config", config);
                        componentEntities.add(component);
                    }
                }
            }
        }
        Iterator<Object> it = fedMappers.iterator();
        while (it.hasNext()) {
            BasicDBObject fedMapper = (BasicDBObject) it.next();
            String id = fedMapper.getString("id");
            if (removedProviders.contains(id)) {
                it.remove();
            }

        }
        realms.update(new BasicDBObject().append("_id", realmId), realm);
    }
}

From source file:org.keycloak.connections.mongo.updater.impl.updates.Update2_3_0.java

License:Apache License

@Override
public void update(KeycloakSession session) {

    DBCollection realms = db.getCollection("realms");
    DBCursor cursor = realms.find();//from  w  ww.  j  a va 2 s  .  co  m
    while (cursor.hasNext()) {
        BasicDBObject realm = (BasicDBObject) cursor.next();

        String realmId = realm.getString("_id");

        String privateKeyPem = realm.getString("privateKeyPem");
        String certificatePem = realm.getString("certificatePem");

        BasicDBList entities = (BasicDBList) realm.get("componentEntities");

        BasicDBObject component = new BasicDBObject();
        component.put("id", KeycloakModelUtils.generateId());
        component.put("name", "rsa");
        component.put("providerType", KeyProvider.class.getName());
        component.put("providerId", "rsa");
        component.put("parentId", realmId);

        BasicDBObject config = new BasicDBObject();
        config.put("priority", Collections.singletonList("100"));
        config.put("privateKey", Collections.singletonList(privateKeyPem));
        config.put("certificate", Collections.singletonList(certificatePem));

        component.put("config", config);

        entities.add(component);

        realm.remove("privateKeyPem");
        realm.remove("certificatePem");
        realm.remove("publicKeyPem");
        realm.remove("codeSecret");

        realms.update(new BasicDBObject().append("_id", realmId), realm);
    }
}

From source file:org.mobicents.servlet.sip.restcomm.dao.mongodb.MongoAccountsDao.java

License:Open Source License

private void updateAccount(final DBCollection collection, final Account account) {
    final BasicDBObject query = new BasicDBObject();
    query.put("sid", account.getSid().toString());
    final WriteResult result = collection.update(query, toDbObject(account));
    if (!result.getLastError().ok()) {
        logger.error(result.getLastError().getErrorMessage());
    }//from   w  w w  .ja  v  a  2 s.c  o  m
}

From source file:org.modeshape.jcr.value.binary.MongodbBinaryStore.java

License:Apache License

/**
 * Modifies content header./*ww  w. j  a v  a 2 s.co m*/
 * 
 * @param content stored content
 * @param fieldName attribute name
 * @param value new value for the attribute
 */
private void setAttribute(DBCollection content, String fieldName, Object value) {
    DBObject header = content.findOne(HEADER);
    BasicDBObject newHeader = new BasicDBObject();

    // clone header
    newHeader.put(FIELD_CHUNK_TYPE, header.get(FIELD_CHUNK_TYPE));
    newHeader.put(FIELD_MIME_TYPE, header.get(FIELD_MIME_TYPE));
    newHeader.put(FIELD_EXTRACTED_TEXT, header.get(FIELD_EXTRACTED_TEXT));
    newHeader.put(FIELD_UNUSED, header.get(FIELD_UNUSED));
    newHeader.put(FIELD_UNUSED_SINCE, header.get(FIELD_UNUSED_SINCE));

    // modify specified field and update record
    newHeader.put(fieldName, value);
    content.update(HEADER, newHeader);
}

From source file:org.mongoj.samples.service.persistence.CarPersistenceImpl.java

License:Open Source License

protected Car updateImpl(org.mongoj.samples.model.Car car) throws UpdateException, SystemException {
    DBCollection collection = getDB().getCollection(CarImpl.COLLECTION_NAME);

    if (car.isNew()) {
        car.setNew(false);/*from w w w. ja  v  a  2  s .  c  o m*/

        CarImpl carImpl = (CarImpl) car;

        carImpl.addMap.clear();
        carImpl.appendMap.clear();
        carImpl.removeMap.clear();
        carImpl.setMap.clear();

        WriteResult writeResult = collection.insert(getDBObject(car));

        String err = writeResult.getError();

        if (err != null) {
            throw new UpdateException(err);
        }
    } else {
        DBObject criteria = new QueryBuilder().put("_id").is(new ObjectId(car.getId())).get();

        CarImpl carImpl = (CarImpl) car;

        BasicDBObjectBuilder updateBuilder = BasicDBObjectBuilder.start();
        BasicDBObjectBuilder setUpdates = BasicDBObjectBuilder.start();
        BasicDBObjectBuilder pushUpdates = BasicDBObjectBuilder.start();
        BasicDBObjectBuilder pushAllUpdates = BasicDBObjectBuilder.start();
        BasicDBObjectBuilder addUpdates = BasicDBObjectBuilder.start();
        BasicDBObjectBuilder removeUpdates = BasicDBObjectBuilder.start();
        BasicDBObjectBuilder removeAllUpdates = BasicDBObjectBuilder.start();

        for (String field : carImpl.setMap.keySet()) {
            setUpdates = setUpdates.add(field, carImpl.setMap.get(field));
        }

        if (!setUpdates.isEmpty()) {
            updateBuilder.add(SET_OPERATOR, setUpdates.get());
        }

        for (String field : carImpl.appendMap.keySet()) {
            List<Object> list = (List<Object>) carImpl.appendMap.get(field);

            if (!list.isEmpty()) {
                if (list.size() == 1) {
                    pushUpdates = pushUpdates.add(field, ((List) carImpl.appendMap.get(field)).get(0));
                } else {
                    pushAllUpdates = pushAllUpdates.add(field, carImpl.appendMap.get(field));
                }
            }
        }

        if (!pushUpdates.isEmpty()) {
            updateBuilder.add(PUSH_OPERATOR, pushUpdates.get());
        }

        if (!pushAllUpdates.isEmpty()) {
            updateBuilder.add(PUSH_ALL_OPERATOR, pushAllUpdates.get());
        }

        for (String field : carImpl.addMap.keySet()) {
            List<Object> list = (List<Object>) carImpl.addMap.get(field);

            if (!list.isEmpty()) {
                if (list.size() == 1) {
                    addUpdates = addUpdates.add(field, ((List) carImpl.addMap.get(field)).get(0));
                } else {
                    DBObject each = BasicDBObjectBuilder.start()
                            .add(EACH_OPERATOR, ((List) carImpl.addMap.get(field)).toArray()).get();

                    addUpdates = addUpdates.add(field, each);
                }
            }
        }

        if (!addUpdates.isEmpty()) {
            updateBuilder.add(ADD_TO_SET_OPERATOR, addUpdates.get());
        }

        for (String field : carImpl.removeMap.keySet()) {
            List<Object> list = (List<Object>) carImpl.removeMap.get(field);

            if (!list.isEmpty()) {
                if (list.size() == 1) {
                    removeUpdates = removeUpdates.add(field, ((List) carImpl.removeMap.get(field)).get(0));
                } else {
                    removeAllUpdates = removeAllUpdates.add(field, carImpl.removeMap.get(field));
                }
            }
        }

        if (!removeUpdates.isEmpty()) {
            updateBuilder.add(PULL_OPERATOR, removeUpdates.get());
        }

        if (!removeAllUpdates.isEmpty()) {
            updateBuilder.add(PULL_ALL_OPERATOR, removeAllUpdates.get());
        }

        if (!updateBuilder.isEmpty()) {
            DBObject update = updateBuilder.get();

            _log.debug("Update query = {}", update);

            WriteResult writeResult = collection.update(criteria, update);

            String err = writeResult.getError();

            if (err != null) {
                throw new UpdateException(err);
            }
        }
    }

    return car;
}

From source file:org.mongoj.samples.service.persistence.UserPersistenceImpl.java

License:Open Source License

protected User updateImpl(org.mongoj.samples.model.User user) throws UpdateException, SystemException {
    DBCollection collection = getDB().getCollection(UserImpl.COLLECTION_NAME);

    if (user.isNew()) {
        user.setNew(false);/*from   w  ww  .  j a  v  a2 s .  co  m*/

        UserImpl userImpl = (UserImpl) user;

        userImpl.addMap.clear();
        userImpl.appendMap.clear();
        userImpl.removeMap.clear();
        userImpl.setMap.clear();

        WriteResult writeResult = collection.insert(getDBObject(user));

        String err = writeResult.getError();

        if (err != null) {
            throw new UpdateException(err);
        }
    } else {
        DBObject criteria = new QueryBuilder().put("_id").is(new ObjectId(user.getId())).get();

        UserImpl userImpl = (UserImpl) user;

        BasicDBObjectBuilder updateBuilder = BasicDBObjectBuilder.start();
        BasicDBObjectBuilder setUpdates = BasicDBObjectBuilder.start();
        BasicDBObjectBuilder pushUpdates = BasicDBObjectBuilder.start();
        BasicDBObjectBuilder pushAllUpdates = BasicDBObjectBuilder.start();
        BasicDBObjectBuilder addUpdates = BasicDBObjectBuilder.start();
        BasicDBObjectBuilder removeUpdates = BasicDBObjectBuilder.start();
        BasicDBObjectBuilder removeAllUpdates = BasicDBObjectBuilder.start();

        for (String field : userImpl.setMap.keySet()) {
            setUpdates = setUpdates.add(field, userImpl.setMap.get(field));
        }

        if (!setUpdates.isEmpty()) {
            updateBuilder.add(SET_OPERATOR, setUpdates.get());
        }

        for (String field : userImpl.appendMap.keySet()) {
            List<Object> list = (List<Object>) userImpl.appendMap.get(field);

            if (!list.isEmpty()) {
                if (list.size() == 1) {
                    pushUpdates = pushUpdates.add(field, ((List) userImpl.appendMap.get(field)).get(0));
                } else {
                    pushAllUpdates = pushAllUpdates.add(field, userImpl.appendMap.get(field));
                }
            }
        }

        if (!pushUpdates.isEmpty()) {
            updateBuilder.add(PUSH_OPERATOR, pushUpdates.get());
        }

        if (!pushAllUpdates.isEmpty()) {
            updateBuilder.add(PUSH_ALL_OPERATOR, pushAllUpdates.get());
        }

        for (String field : userImpl.addMap.keySet()) {
            List<Object> list = (List<Object>) userImpl.addMap.get(field);

            if (!list.isEmpty()) {
                if (list.size() == 1) {
                    addUpdates = addUpdates.add(field, ((List) userImpl.addMap.get(field)).get(0));
                } else {
                    DBObject each = BasicDBObjectBuilder.start()
                            .add(EACH_OPERATOR, ((List) userImpl.addMap.get(field)).toArray()).get();

                    addUpdates = addUpdates.add(field, each);
                }
            }
        }

        if (!addUpdates.isEmpty()) {
            updateBuilder.add(ADD_TO_SET_OPERATOR, addUpdates.get());
        }

        for (String field : userImpl.removeMap.keySet()) {
            List<Object> list = (List<Object>) userImpl.removeMap.get(field);

            if (!list.isEmpty()) {
                if (list.size() == 1) {
                    removeUpdates = removeUpdates.add(field, ((List) userImpl.removeMap.get(field)).get(0));
                } else {
                    removeAllUpdates = removeAllUpdates.add(field, userImpl.removeMap.get(field));
                }
            }
        }

        if (!removeUpdates.isEmpty()) {
            updateBuilder.add(PULL_OPERATOR, removeUpdates.get());
        }

        if (!removeAllUpdates.isEmpty()) {
            updateBuilder.add(PULL_ALL_OPERATOR, removeAllUpdates.get());
        }

        if (!updateBuilder.isEmpty()) {
            DBObject update = updateBuilder.get();

            _log.debug("Update query = {}", update);

            WriteResult writeResult = collection.update(criteria, update);

            String err = writeResult.getError();

            if (err != null) {
                throw new UpdateException(err);
            }
        }
    }

    return user;
}

From source file:org.mongolink.domain.updateStrategy.DiffStrategy.java

License:Open Source License

@Override
public void update(DBObject initialValue, DBObject updatedValue, DBCollection collection) {
    final DBObject diff = new DbObjectDiff(initialValue).compareWith(updatedValue);
    final DBObject q = updateQuery(initialValue);
    executePushAndPull(collection, diff, q);
    if (!diff.keySet().isEmpty()) {
        LOGGER.debug("Updating : collection {} : query {} : modifiers : {}", collection.getName(), q, diff);
        collection.update(q, diff);
    }/*  w ww  .  ja v  a  2  s  .  c o  m*/
}

From source file:org.mongolink.domain.updateStrategy.DiffStrategy.java

License:Open Source License

private void execute(DbObjectDiff.Modifier modifier, DBCollection collection, DBObject diff, DBObject q) {
    final DBObject modifications = (DBObject) diff.get(modifier.toString());
    diff.removeField(modifier.toString());
    if (modifications != null) {
        LOGGER.debug("Updating array : {} modifier: {}  values: {}", q, modifier, modifications);
        collection.update(q, new BasicDBObject(modifier.toString(), modifications));
    }/*w w w .j a  va 2s  .  c  om*/
}

From source file:org.mongolink.domain.updateStrategy.OverwriteStrategy.java

License:Open Source License

@Override
public void update(DBObject initialValue, DBObject updatedValue, DBCollection collection) {
    DBObject query = new BasicDBObject();
    query.put("_id", updatedValue.get("_id"));
    LOGGER.debug("Updating : collection {} : element {}", collection.getName(), updatedValue);
    collection.update(updateQuery(initialValue), updatedValue);
}

From source file:org.opendaylight.controller.samples.onftappingapp.CaptureDev.java

License:Apache License

public static boolean adjustReferenceCount(final ReferenceCountEnum adjType, String switchEntryId)
        throws NotFoundException {

    DB database = TappingApp.getDatabase();
    DBCollection table = database.getCollection(DatabaseNames.getCaptureDevTableName());

    // Look for the CaptureDev object by object ID in the database
    BasicDBObject searchQuery = new BasicDBObject();
    ObjectId id = new ObjectId(switchEntryId);
    searchQuery.put("_id", id);
    DBObject dbObj = table.findOne(searchQuery);

    if (dbObj == null)
        throw new NotFoundException();

    // create an increment query
    DBObject modifier = new BasicDBObject("refCount", (adjType == ReferenceCountEnum.DECREMENT) ? -1 : 1);
    DBObject incQuery = new BasicDBObject("$inc", modifier);

    // increment a counter value atomically
    WriteResult result = table.update(searchQuery, incQuery);
    return (result != null) ? true : false;
}