Search in sources :

Example 16 with UpdateOptions

use of com.mongodb.client.model.UpdateOptions in project duangframework by tcrct.

the class MongoBaseDao method update.

/**
 * 根据条件更新记录
 * @param mongoQuery			查询条件
 * @param mongoUpdate		更新内容
 * @return		成功更新的记录数
 * @throws Exception
 */
@Override
public long update(MongoQuery mongoQuery, MongoUpdate mongoUpdate) throws Exception {
    Bson queryBson = mongoQuery.getQueryBson();
    Bson updateBson = mongoUpdate.getUpdateBson();
    if (ToolsKit.isEmpty(queryBson) || ToolsKit.isEmpty(updateBson)) {
        throw new MongodbException("Mongodb Update is Fail: queryBson or updateBson is null");
    }
    // 3.5以上的版体写法,为了支持3.5以下的版本,故注释掉
    // BsonDocument bsonDocument = document.toBsonDocument(cls, collection.getCodecRegistry());
    // 查询记录不存在时,不新增记录
    UpdateOptions options = new UpdateOptions();
    options.upsert(false);
    UpdateResult updateResult = collection.updateOne(queryBson, updateBson, options);
    return updateResult.isModifiedCountAvailable() ? updateResult.getModifiedCount() : 0L;
}
Also used : UpdateOptions(com.mongodb.client.model.UpdateOptions) UpdateResult(com.mongodb.client.result.UpdateResult) Bson(org.bson.conversions.Bson) MongodbException(com.duangframework.core.exceptions.MongodbException)

Example 17 with UpdateOptions

use of com.mongodb.client.model.UpdateOptions in project drill by apache.

the class MongoPersistentStore method putIfAbsent.

@Override
public boolean putIfAbsent(String key, V value) {
    try {
        Bson query = Filters.eq(DrillMongoConstants.ID, key);
        Bson update = Updates.set(pKey, bytes(value));
        UpdateResult updateResult = collection.updateOne(query, update, new UpdateOptions().upsert(true));
        return updateResult.getModifiedCount() == 1;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new DrillRuntimeException(e.getMessage(), e);
    }
}
Also used : DrillRuntimeException(org.apache.drill.common.exceptions.DrillRuntimeException) UpdateResult(com.mongodb.client.result.UpdateResult) UpdateOptions(com.mongodb.client.model.UpdateOptions) IOException(java.io.IOException) DrillRuntimeException(org.apache.drill.common.exceptions.DrillRuntimeException) NoSuchElementException(java.util.NoSuchElementException) Bson(org.bson.conversions.Bson)

Example 18 with UpdateOptions

use of com.mongodb.client.model.UpdateOptions in project legendarybot by greatman.

the class WoWLinkPlugin method start.

@Override
public void start() {
    // Load the configuration
    props = new Properties();
    try {
        props.load(new FileInputStream("app.properties"));
    } catch (java.io.IOException e) {
        e.printStackTrace();
        getBot().getStacktraceHandler().sendStacktrace(e);
    }
    path("/auth", () -> get("/battlenetcallback", (req, res) -> {
        String state = req.queryParams("state");
        String region = state.split(":")[0];
        OAuth20Service service = new ServiceBuilder(props.getProperty("battlenetoauth.key")).apiSecret(props.getProperty("battlenetoauth.secret")).scope("wow.profile").callback("https://legendarybot.greatmancode.com/auth/battlenetcallback").build(new OAuthBattleNetApi(region));
        String oAuthCode = req.queryParams("code");
        // TODO: Save oauth code to do a character refresh.
        OAuth2AccessToken token = service.getAccessToken(oAuthCode);
        OAuthRequest request = new OAuthRequest(Verb.GET, "https://" + region + ".api.battle.net/wow/user/characters");
        service.signRequest(token, request);
        Response response = service.execute(request);
        JSONParser parser = new JSONParser();
        JSONObject obj = (JSONObject) parser.parse(response.getBody());
        JSONArray charactersArray = (JSONArray) obj.get("characters");
        List<WoWCharacter> characterList = new ArrayList<>();
        charactersArray.forEach((c) -> {
            JSONObject jsonObject = (JSONObject) c;
            if (jsonObject.containsKey("guild")) {
                characterList.add(new WoWCharacter((String) jsonObject.get("name"), ((String) jsonObject.get("realm")).toLowerCase(), (String) jsonObject.get("guild"), region, HeroClass.values()[((Long) jsonObject.get("class")).intValue()]));
                log.info("User " + state.split(":")[1] + " user have the character " + jsonObject.get("name") + " in guild " + jsonObject.get("guild"));
            }
        });
        if (characterList.size() > 0) {
            MongoCollection<Document> collection = getBot().getMongoDatabase().getCollection(MONGO_WOW_CHARACTERS_COLLECTION);
            characterList.forEach((c) -> collection.updateOne(and(eq("region", c.getRegion()), eq("realm", c.getRealm()), eq("name", c.getCharacterName())), and(set("guild", c.getGuild()), set("owner", state.split(":")[1])), new UpdateOptions().upsert(true)));
        }
        return "Your WoW characters are now synced to LegendaryBot!";
    }));
    getBot().getCommandHandler().addCommand("linkwowchars", new LinkWoWCharsCommand(this), "World of Warcraft Character");
    getBot().getCommandHandler().addCommand("guildchars", new GuildCharsCommand(this), "World of Warcraft Character");
    getBot().getCommandHandler().addCommand("setmainchar", new SetMainCharacterCommand(this), "World of Warcraft Character");
    getBot().getCommandHandler().addCommand("enableautorank", new EnableAutoRankCommand(this), "WoW Admin Commands");
    getBot().getCommandHandler().addCommand("disableautorank", new DisableAutoRankCommand(this), "WoW Admin Commands");
    getBot().getCommandHandler().addCommand("setwowrank", new SetWoWRankCommand(this), "WoW Admin Commands");
    getBot().getCommandHandler().addCommand("syncrank", new SyncRankCommand(this), "World of Warcraft Character");
    getBot().getCommandHandler().addCommand("syncguild", new SyncGuildCommand(this), "WoW Admin Commands");
    getBot().getCommandHandler().addCommand("enableautorankupdate", new EnableAutoRankUpdateCommand(this), "WoW Admin Commands");
    getBot().getCommandHandler().addCommand("disableautorankupdate", new DisableAutoRankUpdateCommand(this), "WoW Admin Commands");
    // We load the scheduler
    getBot().getJDA().forEach((jda -> {
        jda.getGuilds().forEach(guild -> {
            if (getBot().getGuildSettings(guild).getSetting(SETTING_SCHEDULER) != null && getBot().getGuildSettings(guild).getSetting(SETTING_RANKSET_ENABLED) != null) {
                scheduler.put(guild.getId(), new SyncRankScheduler(this, guild));
            }
        });
    }));
}
Also used : OAuthBattleNetApi(com.greatmancode.legendarybot.plugins.wowlink.utils.OAuthBattleNetApi) Document(org.bson.Document) Spark.get(spark.Spark.get) java.util(java.util) ServiceBuilder(com.github.scribejava.core.builder.ServiceBuilder) WoWCharacter(com.greatmancode.legendarybot.plugins.wowlink.utils.WoWCharacter) MongoCollection(com.mongodb.client.MongoCollection) LegendaryBotPlugin(com.greatmancode.legendarybot.api.plugin.LegendaryBotPlugin) LoggerFactory(org.slf4j.LoggerFactory) OAuth20Service(com.github.scribejava.core.oauth.OAuth20Service) BattleNetAPIInterceptor(com.greatmancode.legendarybot.api.utils.BattleNetAPIInterceptor) HeroClass(com.greatmancode.legendarybot.api.utils.HeroClass) Spark.path(spark.Spark.path) JSONArray(org.json.simple.JSONArray) PluginWrapper(org.pf4j.PluginWrapper) com.greatmancode.legendarybot.plugins.wowlink.commands(com.greatmancode.legendarybot.plugins.wowlink.commands) PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) Filters.and(com.mongodb.client.model.Filters.and) ParseException(org.json.simple.parser.ParseException) OAuth2AccessToken(com.github.scribejava.core.model.OAuth2AccessToken) GuildSettings(com.greatmancode.legendarybot.api.server.GuildSettings) ResultSet(java.sql.ResultSet) Filters.eq(com.mongodb.client.model.Filters.eq) UpdateOptions(com.mongodb.client.model.UpdateOptions) Updates.unset(com.mongodb.client.model.Updates.unset) Role(net.dv8tion.jda.core.entities.Role) Request(okhttp3.Request) Logger(org.slf4j.Logger) JSONParser(org.json.simple.parser.JSONParser) Verb(com.github.scribejava.core.model.Verb) IOException(java.io.IOException) Filters.exists(com.mongodb.client.model.Filters.exists) FileInputStream(java.io.FileInputStream) Updates.set(com.mongodb.client.model.Updates.set) Guild(net.dv8tion.jda.core.entities.Guild) OkHttpClient(okhttp3.OkHttpClient) JSONObject(org.json.simple.JSONObject) OAuthRequest(com.github.scribejava.core.model.OAuthRequest) Block(com.mongodb.Block) User(net.dv8tion.jda.core.entities.User) Response(com.github.scribejava.core.model.Response) HttpUrl(okhttp3.HttpUrl) Spark(spark.Spark) OAuthRequest(com.github.scribejava.core.model.OAuthRequest) UpdateOptions(com.mongodb.client.model.UpdateOptions) OAuth20Service(com.github.scribejava.core.oauth.OAuth20Service) ServiceBuilder(com.github.scribejava.core.builder.ServiceBuilder) OAuth2AccessToken(com.github.scribejava.core.model.OAuth2AccessToken) WoWCharacter(com.greatmancode.legendarybot.plugins.wowlink.utils.WoWCharacter) JSONArray(org.json.simple.JSONArray) IOException(java.io.IOException) OAuthBattleNetApi(com.greatmancode.legendarybot.plugins.wowlink.utils.OAuthBattleNetApi) FileInputStream(java.io.FileInputStream) Response(com.github.scribejava.core.model.Response) MongoCollection(com.mongodb.client.MongoCollection) JSONObject(org.json.simple.JSONObject) JSONParser(org.json.simple.parser.JSONParser)

Example 19 with UpdateOptions

use of com.mongodb.client.model.UpdateOptions in project legendarybot by greatman.

the class ILegendaryBot method convertDatabase.

private void convertDatabase() {
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
    config.addDataSourceProperty("serverName", System.getenv("MYSQL_ADDRESS") != null ? System.getenv("MYSQL_ADDRESS") : props.getProperty("mysql.address"));
    config.addDataSourceProperty("port", System.getenv("MYSQL_PORT") != null ? System.getenv("MYSQL_PORT") : props.getProperty("mysql.port"));
    config.addDataSourceProperty("databaseName", System.getenv("MYSQL_DATABASE") != null ? System.getenv("MYSQL_DATABASE") : props.getProperty("mysql.database"));
    config.addDataSourceProperty("user", System.getenv("MYSQL_USER") != null ? System.getenv("MYSQL_USER") : props.getProperty("mysql.user"));
    config.addDataSourceProperty("password", System.getenv("MYSQL_PASSWORD") != null ? System.getenv("MYSQL_PASSWORD") : props.getProperty("mysql.password"));
    config.setConnectionTimeout(5000);
    config.addDataSourceProperty("characterEncoding", "utf8");
    config.addDataSourceProperty("useUnicode", "true");
    HikariDataSource dataSource = new HikariDataSource(config);
    try {
        Connection connection = dataSource.getConnection();
        log.info("Converting guild_config table to guild collection");
        PreparedStatement statement = connection.prepareStatement("SELECT * FROM guild_config");
        MongoCollection<Document> mongoCollection = getMongoDatabase().getCollection("guild");
        ResultSet set = statement.executeQuery();
        while (set.next()) {
            if (set.getString("configName").equals("")) {
                continue;
            }
            String value = set.getString("configValue");
            if (set.getString("configName").equals("WOW_SERVER_NAME")) {
                value = value.toLowerCase();
            }
            mongoCollection.updateOne(eq("guild_id", set.getString("guildId")), set("settings." + set.getString("configName"), value), new UpdateOptions().upsert(true));
        }
        set.close();
        statement.close();
        log.info("Converting guild_commands");
        statement = connection.prepareStatement("SELECT * FROM guild_commands");
        set = statement.executeQuery();
        while (set.next()) {
            if (set.getString("command_name").equals("")) {
                continue;
            }
            mongoCollection.updateOne(eq("guild_id", set.getString("guild_id")), set("customCommands." + set.getString("command_name"), set.getString("text")), new UpdateOptions().upsert(true));
        }
        set.close();
        statement.close();
        mongoCollection = getMongoDatabase().getCollection("wowCharacters");
        log.info("Converting legendarycheck");
        statement = connection.prepareStatement("SELECT * FROM legendarycheck");
        set = statement.executeQuery();
        while (set.next()) {
            Document document = new Document("name", set.getString("playerName")).append("realm", set.getString("serverName")).append("region", set.getString("region")).append("lastUpdate", set.getLong("lastModified"));
            mongoCollection.insertOne(document);
        }
        set.close();
        statement.close();
        log.info("Converting user_characters");
        statement = connection.prepareStatement("SELECT * FROM user_characters");
        set = statement.executeQuery();
        while (set.next()) {
            mongoCollection.updateOne(and(eq("name", set.getString("characterName")), eq("region", set.getString("region")), eq("realm", set.getString("realmName").toLowerCase())), and(set("guild", set.getString("guildName")), set("owner", set.getString("user_id"))), new UpdateOptions().upsert(true));
        }
        set.close();
        statement.close();
        log.info("Converting user_characters_guild");
        statement = connection.prepareStatement("SELECT * FROM user_characters_guild");
        set = statement.executeQuery();
        while (set.next()) {
            String guildId = set.getString("guild_id");
            MongoCollection<Document> mongoCollectionGuild = getMongoDatabase().getCollection("guild");
            Document guildDocument = mongoCollectionGuild.find(eq("guild_id", guildId)).first();
            Document settingsDocument = (Document) guildDocument.get("settings");
            String region = settingsDocument.getString("WOW_REGION_NAME");
            String realm = settingsDocument.getString("WOW_SERVER_NAME");
            if (region != null && realm != null) {
                realm = realm.toLowerCase();
                mongoCollection.updateOne(and(eq("realm", realm), eq("region", region), eq("name", set.getString("characterName"))), set("guild_id", set.getString("guild_id")));
            }
        }
        set.close();
        statement.close();
        connection.close();
        dataSource.close();
        log.info("Convert done. LegendaryBot is now using the MongoDB database.");
    } catch (SQLException e) {
        e.printStackTrace();
        System.exit(1);
    }
}
Also used : HikariDataSource(com.zaxxer.hikari.HikariDataSource) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) HikariConfig(com.zaxxer.hikari.HikariConfig) Document(org.bson.Document) UpdateOptions(com.mongodb.client.model.UpdateOptions)

Example 20 with UpdateOptions

use of com.mongodb.client.model.UpdateOptions in project mongo-java-driver by mongodb.

the class JsonPoweredCrudTestHelper method getUpdateManyResult.

BsonDocument getUpdateManyResult(final BsonDocument collectionOptions, final BsonDocument arguments, @Nullable final ClientSession clientSession) {
    UpdateOptions options = new UpdateOptions();
    if (arguments.containsKey("upsert")) {
        options.upsert(arguments.getBoolean("upsert").getValue());
    }
    if (arguments.containsKey("collation")) {
        options.collation(getCollation(arguments.getDocument("collation")));
    }
    if (arguments.containsKey("arrayFilters")) {
        options.arrayFilters((getListOfDocuments(arguments.getArray("arrayFilters"))));
    }
    if (arguments.containsKey("bypassDocumentValidation")) {
        options.bypassDocumentValidation(arguments.getBoolean("bypassDocumentValidation").getValue());
    }
    if (arguments.containsKey("hint")) {
        if (arguments.isDocument("hint")) {
            options.hint(arguments.getDocument("hint"));
        } else {
            options.hintString(arguments.getString("hint").getValue());
        }
    }
    UpdateResult updateResult;
    if (clientSession == null) {
        if (arguments.isDocument("update")) {
            updateResult = getCollection(collectionOptions).updateMany(arguments.getDocument("filter"), arguments.getDocument("update"), options);
        } else {
            // update is a pipeline
            updateResult = getCollection(collectionOptions).updateMany(arguments.getDocument("filter"), getListOfDocuments(arguments.getArray("update")), options);
        }
    } else {
        if (arguments.isDocument("update")) {
            updateResult = getCollection(collectionOptions).updateMany(clientSession, arguments.getDocument("filter"), arguments.getDocument("update"), options);
        } else {
            // update is a pipeline
            updateResult = getCollection(collectionOptions).updateMany(clientSession, arguments.getDocument("filter"), getListOfDocuments(arguments.getArray("update")), options);
        }
    }
    return toResult(updateResult);
}
Also used : UpdateOptions(com.mongodb.client.model.UpdateOptions) FindOneAndUpdateOptions(com.mongodb.client.model.FindOneAndUpdateOptions) UpdateResult(com.mongodb.client.result.UpdateResult)

Aggregations

UpdateOptions (com.mongodb.client.model.UpdateOptions)53 Document (org.bson.Document)31 FindOneAndUpdateOptions (com.mongodb.client.model.FindOneAndUpdateOptions)21 Bson (org.bson.conversions.Bson)17 UpdateResult (com.mongodb.client.result.UpdateResult)10 Test (org.junit.jupiter.api.Test)10 BasicQuery (org.springframework.data.mongodb.core.query.BasicQuery)8 ArrayList (java.util.ArrayList)6 BsonDocument (org.bson.BsonDocument)6 Test (org.junit.Test)6 Update (org.springframework.data.mongodb.core.query.Update)4 BasicDBObject (com.mongodb.BasicDBObject)3 MongoCollection (com.mongodb.client.MongoCollection)3 CountOptions (com.mongodb.client.model.CountOptions)3 IOException (java.io.IOException)3 List (java.util.List)3 BsonValue (org.bson.BsonValue)3 ObjectId (org.bson.types.ObjectId)3 MongodbException (com.duangframework.core.exceptions.MongodbException)2 Block (com.mongodb.Block)2