Search in sources :

Example 86 with ResultSet

use of com.datastax.driver.core.ResultSet in project FlareBot by FlareBot.

the class FlareBotManager method loadPlaylist.

public ArrayList<String> loadPlaylist(TextChannel channel, User sender, String name) {
    final ArrayList<String> list = new ArrayList<>();
    CassandraController.runTask(session -> {
        if (loadPlaylistStatement == null)
            loadPlaylistStatement = session.prepare("SELECT songs FROM " + "flarebot.playlist WHERE playlist_name = ? AND guild_id = ?");
        ResultSet set = session.execute(loadPlaylistStatement.bind().setString(0, name).setString(1, channel.getGuild().getId()));
        Row row = set.one();
        if (row != null) {
            list.addAll(row.getList("songs", String.class));
        } else
            channel.sendMessage(MessageUtils.getEmbed(sender).setDescription("That playlist does not exist!").build()).queue();
    });
    return list;
}
Also used : ArrayList(java.util.ArrayList) ResultSet(com.datastax.driver.core.ResultSet) Row(com.datastax.driver.core.Row)

Example 87 with ResultSet

use of com.datastax.driver.core.ResultSet in project FlareBot by FlareBot.

the class GuildWrapperLoader method load.

@Override
@ParametersAreNonnullByDefault
public GuildWrapper load(String id) {
    long start = System.currentTimeMillis();
    ResultSet set = CassandraController.execute("SELECT data FROM " + FlareBotManager.instance().GUILD_DATA_TABLE + " WHERE guild_id = '" + id + "'");
    GuildWrapper wrapper;
    Row row = set != null ? set.one() : null;
    String json = null;
    JSONConfig data;
    try {
        if (row != null) {
            json = row.getString("data");
            if (json.isEmpty() || json.equalsIgnoreCase("null")) {
                return new GuildWrapper(id);
            }
            data = new JSONConfig(parser.parse(json).getAsJsonObject(), '.', ALLOWED_SPECIAL_CHARACTERS);
            if (data.getLong("dataVersion").isPresent() && data.getLong("dataVersion").getAsLong() == 0)
                data = firstMigration(data);
            wrapper = FlareBot.GSON.fromJson(data.getObject().toString(), GuildWrapper.class);
        } else
            return new GuildWrapper(id);
    } catch (Exception e) {
        if (json == null) {
            FlareBot.LOGGER.error(Markers.TAG_DEVELOPER, "Failed to load GuildWrapper!!\n" + "Guild ID: " + id + "\n" + "Guild JSON: " + (row != null ? row.getString("data") : "New guild data!") + "\n" + "Error: " + e.getMessage(), e);
            return null;
        }
        try {
            data = new JSONConfig(parser.parse(json).getAsJsonObject(), '.', ALLOWED_SPECIAL_CHARACTERS);
        } catch (Exception e1) {
            FlareBot.LOGGER.error(Markers.TAG_DEVELOPER, "Failed to load GuildWrapper!!\n" + "Guild ID: " + id + "\n" + "Guild JSON: " + json + "\n" + "Error: " + e.getMessage(), e);
            throw new IllegalArgumentException("Invalid JSON! '" + json + "'", e1);
        }
        if (!data.getLong("dataVersion").isPresent()) {
            try {
                data = firstMigration(data);
            } catch (Exception e1) {
                FlareBot.LOGGER.error(Markers.TAG_DEVELOPER, "Failed to load GuildWrapper!!\n" + "Guild ID: " + id + "\n" + "Guild JSON: " + json + "\n" + "Error: " + e.getMessage(), e);
                throw new IllegalArgumentException("Invalid JSON! '" + json + "'", e1);
            }
            data.set("dataVersion", 1);
        }
        long version = data.getLong("dataVersion").getAsLong();
        if (version != GuildWrapper.DATA_VERSION) {
        // Migrations
        }
        json = data.getObject().toString();
        try {
            wrapper = FlareBot.GSON.fromJson(json, GuildWrapper.class);
        } catch (Exception e1) {
            FlareBot.LOGGER.error(Markers.TAG_DEVELOPER, "Failed to load GuildWrapper!!\n" + "Guild ID: " + id + "\n" + "Guild JSON: " + json + "\n" + "Error: " + e1.getMessage(), e1);
            return null;
        }
    }
    long total = (System.currentTimeMillis() - start);
    loadTimes.add(total);
    if (total >= 200) {
        Constants.getImportantLogChannel().sendMessage(MessageUtils.getEmbed().setColor(new Color(166, 0, 255)).setTitle("Long guild load time!", null).setDescription("Guild " + id + " loaded!").addField("Time", "Millis: " + System.currentTimeMillis() + "\nTime: " + LocalDateTime.now().toString(), false).addField("Load time", total + "ms", false).build()).queue();
    }
    return wrapper;
}
Also used : Color(java.awt.Color) ResultSet(com.datastax.driver.core.ResultSet) JSONConfig(io.github.binaryoverload.JSONConfig) Row(com.datastax.driver.core.Row) ParametersAreNonnullByDefault(javax.annotation.ParametersAreNonnullByDefault)

Example 88 with ResultSet

use of com.datastax.driver.core.ResultSet in project FlareBot by FlareBot.

the class EvalCommand method onCommand.

@Override
public void onCommand(User sender, GuildWrapper guild, TextChannel channel, Message message, String[] args, Member member) {
    if (args.length == 0) {
        channel.sendMessage("Eval something at least smh!").queue();
        return;
    }
    String imports = IMPORTS.stream().map(s -> "import " + s + ".*;").collect(Collectors.joining("\n"));
    ScriptEngine engine = manager.getEngineByName("groovy");
    engine.put("channel", channel);
    engine.put("guild", guild);
    engine.put("message", message);
    engine.put("jda", sender.getJDA());
    engine.put("sender", sender);
    String msg = MessageUtils.getMessage(args);
    final String[] code = { getCode(args) };
    boolean silent = hasOption(Options.SILENT, msg);
    if (hasOption(Options.SNIPPET, msg)) {
        String snippetName = MessageUtils.getNextArgument(msg, Options.SNIPPET.getAsArgument());
        if (snippetName == null) {
            MessageUtils.sendErrorMessage("Please specify the snippet you wish to run! Do `-snippet (name)`", channel);
            return;
        }
        CassandraController.runTask(session -> {
            ResultSet set = session.execute("SELECT encoded_code FROM flarebot.eval_snippets WHERE snippet_name = '" + snippetName + "'");
            Row row = set.one();
            if (row != null) {
                code[0] = StringUtils.newStringUtf8(Base64.getDecoder().decode(row.getString("encoded_code").getBytes()));
            } else {
                MessageUtils.sendErrorMessage("That eval snippet does not exist!", channel);
                code[0] = null;
            }
        });
    }
    if (hasOption(Options.SAVE, msg)) {
        String base64 = Base64.getEncoder().encodeToString(code[0].getBytes());
        CassandraController.runTask(session -> {
            String snippetName = MessageUtils.getNextArgument(msg, Options.SAVE.getAsArgument());
            if (snippetName == null) {
                MessageUtils.sendErrorMessage("Please specify the name of the snippet to save! Do `-save (name)`", channel);
                return;
            }
            if (insertSnippet == null)
                insertSnippet = session.prepare("UPDATE flarebot.eval_snippets SET encoded_code = ? WHERE snippet_name = ?");
            session.execute(insertSnippet.bind().setString(0, base64).setString(1, snippetName));
            MessageUtils.sendSuccessMessage("Saved the snippet `" + snippetName + "`!", channel);
        });
        return;
    }
    if (hasOption(Options.LIST, msg)) {
        ResultSet set = CassandraController.execute("SELECT snippet_name FROM flarebot.eval_snippets");
        if (set == null)
            return;
        MessageUtils.sendInfoMessage("**Available eval snippets**\n" + set.all().stream().map(row -> "`" + row.getString("snippet_name") + "`").collect(Collectors.joining(", ")), channel);
        return;
    }
    if (code[0] == null)
        return;
    final String finalCode = code[0];
    POOL.submit(() -> {
        try {
            String eResult = String.valueOf(engine.eval(imports + '\n' + finalCode));
            if (eResult.length() > 2000) {
                eResult = String.format("Eval too large, result pasted: %s", MessageUtils.paste(eResult));
            }
            if (!silent)
                channel.sendMessage(eResult).queue();
        } catch (Exception e) {
            // FlareBot.LOGGER.error("Error occurred in the evaluator thread pool! " + e.getMessage(), e, Markers.NO_ANNOUNCE);
            channel.sendMessage(MessageUtils.getEmbed(sender).addField("Result: ", "```bf\n" + e.getMessage() + "```", false).build()).queue();
        }
    });
}
Also used : Arrays(java.util.Arrays) Member(net.dv8tion.jda.core.entities.Member) Row(com.datastax.driver.core.Row) TextChannel(net.dv8tion.jda.core.entities.TextChannel) ScriptEngineManager(javax.script.ScriptEngineManager) GuildWrapper(stream.flarebot.flarebot.objects.GuildWrapper) Collectors(java.util.stream.Collectors) Message(net.dv8tion.jda.core.entities.Message) InternalCommand(stream.flarebot.flarebot.commands.InternalCommand) Executors(java.util.concurrent.Executors) PreparedStatement(com.datastax.driver.core.PreparedStatement) Base64(java.util.Base64) List(java.util.List) ResultSet(com.datastax.driver.core.ResultSet) CassandraController(stream.flarebot.flarebot.database.CassandraController) Matcher(java.util.regex.Matcher) User(net.dv8tion.jda.core.entities.User) ScriptEngine(javax.script.ScriptEngine) StringUtils(org.apache.commons.codec.binary.StringUtils) MessageUtils(stream.flarebot.flarebot.util.MessageUtils) Pattern(java.util.regex.Pattern) CommandType(stream.flarebot.flarebot.commands.CommandType) ExecutorService(java.util.concurrent.ExecutorService) ResultSet(com.datastax.driver.core.ResultSet) Row(com.datastax.driver.core.Row) ScriptEngine(javax.script.ScriptEngine)

Example 89 with ResultSet

use of com.datastax.driver.core.ResultSet in project FlareBot by FlareBot.

the class DeleteCommand method onCommand.

@Override
public void onCommand(User sender, GuildWrapper guild, TextChannel channel, Message message, String[] args, Member member) {
    if (args.length == 0) {
        MessageUtils.sendUsage(this, channel, sender, args);
        return;
    }
    channel.sendTyping().complete();
    String name = MessageUtils.getMessage(args, 0);
    CassandraController.runTask(session -> {
        ResultSet set = session.execute(session.prepare("SELECT playlist_name FROM flarebot.playlist WHERE playlist_name = ? AND guild_id = ?").bind().setString(0, name).setString(1, channel.getGuild().getId()));
        if (set.one() != null) {
            session.execute(session.prepare("DELETE FROM flarebot.playlist WHERE playlist_name = ? AND guild_id = ?").bind().setString(0, name).setString(1, channel.getGuild().getId()));
            channel.sendMessage(MessageUtils.getEmbed(sender).setDescription(String.format("Removed the playlist '%s'", name)).setColor(Color.green).build()).queue();
        } else {
            MessageUtils.sendErrorMessage(String.format("The playlist '%s' does not exist!", name), channel, sender);
        }
    });
}
Also used : ResultSet(com.datastax.driver.core.ResultSet)

Example 90 with ResultSet

use of com.datastax.driver.core.ResultSet in project apex-malhar by apache.

the class CassandraTransactionalStore method getCommittedWindowId.

@Override
public long getCommittedWindowId(String appId, int operatorId) {
    try {
        BoundStatement boundStatement = new BoundStatement(lastWindowFetchCommand);
        lastWindowFetchStatement = boundStatement.bind(appId, operatorId);
        long lastWindow = -1;
        ResultSet resultSet = session.execute(lastWindowFetchStatement);
        if (!resultSet.isExhausted()) {
            lastWindow = resultSet.one().getLong(0);
        }
        lastWindowFetchCommand.disableTracing();
        return lastWindow;
    } catch (DriverException ex) {
        throw new RuntimeException(ex);
    }
}
Also used : ResultSet(com.datastax.driver.core.ResultSet) DriverException(com.datastax.driver.core.exceptions.DriverException) BoundStatement(com.datastax.driver.core.BoundStatement)

Aggregations

ResultSet (com.datastax.driver.core.ResultSet)95 Row (com.datastax.driver.core.Row)61 Test (org.junit.Test)43 ArrayList (java.util.ArrayList)17 BoundStatement (com.datastax.driver.core.BoundStatement)13 Session (com.datastax.driver.core.Session)12 Cluster (com.datastax.driver.core.Cluster)10 Statement (com.datastax.driver.core.Statement)8 List (java.util.List)8 PreparedStatement (com.datastax.driver.core.PreparedStatement)7 ByteBuffer (java.nio.ByteBuffer)5 StaticBuffer (org.janusgraph.diskstorage.StaticBuffer)5 BatchStatement (com.datastax.driver.core.BatchStatement)4 ResultSetFuture (com.datastax.driver.core.ResultSetFuture)4 Select (com.datastax.driver.core.querybuilder.Select)4 Tuple (io.vavr.Tuple)4 IOException (java.io.IOException)4 HashSet (java.util.HashSet)4 TypeHint (org.apache.flink.api.common.typeinfo.TypeHint)4 Entry (org.janusgraph.diskstorage.Entry)4