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;
}
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);
}
}
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));
}
});
}));
}
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);
}
}
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);
}
Aggregations