Example usage for com.google.gson JsonElement getAsString

List of usage examples for com.google.gson JsonElement getAsString

Introduction

In this page you can find the example usage for com.google.gson JsonElement getAsString.

Prototype

public String getAsString() 

Source Link

Document

convenience method to get this element as a string value.

Usage

From source file:ch.cyberduck.core.dropbox.DropboxExceptionMappingService.java

License:Open Source License

private void parse(final StringBuilder buffer, final String message) {
    final JsonParser parser = new JsonParser();
    try {//from w  w w .  jav a2  s .  com
        final JsonElement element = parser.parse(new StringReader(message));
        if (element.isJsonObject()) {
            final JsonObject json = element.getAsJsonObject();
            final JsonObject error = json.getAsJsonObject("error");
            if (null == error) {
                this.append(buffer, message);
            } else {
                final JsonPrimitive tag = error.getAsJsonPrimitive(".tag");
                if (null == tag) {
                    this.append(buffer, message);
                } else {
                    this.append(buffer, StringUtils.replace(tag.getAsString(), "_", " "));
                }
            }
        }
        if (element.isJsonPrimitive()) {
            this.append(buffer, element.getAsString());
        }
    } catch (JsonParseException e) {
        // Ignore
    }
}

From source file:ch.jamiete.hilda.admin.AdminPlugin.java

License:Apache License

@Override
public void onLoad() {
    final Configuration servcfg = this.getHilda().getConfigurationManager().getConfiguration(this,
            "allowedservers");
    final JsonArray servarr = servcfg.get().getAsJsonArray("servers");

    if (servarr != null) {

        for (final JsonElement elem : servarr) {
            this.getHilda().addAllowedServer(elem.getAsString());
        }//ww w  . j  a  va 2  s. co  m

        Hilda.getLogger().info("Allowed " + servarr.size() + " server IDs.");
    }
}

From source file:ch.jamiete.hilda.admin.AdminPlugin.java

License:Apache License

@Override
public void onEnable() {
    this.getHilda().getCommandManager().registerChannelCommand(new AdminBaseCommand(this.getHilda(), this));
    this.getHilda().getCommandManager().registerChannelCommand(new ReportCommand(this.getHilda(), this));
    this.getHilda().getCommandManager().registerChannelCommand(new SetupCommand(this.getHilda(), this));

    this.getHilda().getBot().addEventListener(new ServerJoinListener(this));

    this.getHilda().getExecutor().scheduleWithFixedDelay(new MemoryMonitor(this), 1, 1, TimeUnit.MINUTES);

    final Configuration config = this.getHilda().getConfigurationManager().getConfiguration(this);

    if (config.get().get("role") == null) {
        config.get().addProperty("role", "");
        Hilda.getLogger().warning("No role specified.");
    }/*  w  w  w.j  a  v  a2s  .c om*/

    if (config.get().get("log") == null) {
        config.get().addProperty("log", "");
        Hilda.getLogger().warning("No log specified.");
    }

    config.save();

    final String cfg_role = config.get().get("role").getAsString();

    if (cfg_role.isEmpty()) {
        Hilda.getLogger().warning("No role specified.");
    } else {
        this.role = this.getHilda().getBot().getRoleById(cfg_role);
    }

    final String cfg_log = config.get().get("log").getAsString();

    if (cfg_log.isEmpty()) {
        Hilda.getLogger().warning("No log specified.");
    } else {
        this.channel = this.getHilda().getBot().getTextChannelById(cfg_log);
    }

    if (this.role == null || this.channel == null) {
        Hilda.getLogger().warning("Not currently configured correctly.");
    }

    final Logger global = Logger.getLogger("");

    for (final Handler h : global.getHandlers()) {
        if (h instanceof LogReporter) {
            h.close();
            global.removeHandler(h);
        }
    }

    this.reporter = new LogReporter(this.channel);
    global.addHandler(this.reporter);

    final Configuration cfg = this.getHilda().getConfigurationManager().getConfiguration(this, "ignoredusers");
    final JsonArray array = cfg.get().getAsJsonArray("users");

    if (array != null) {

        for (final JsonElement anArray : array) {
            this.getHilda().getCommandManager().addIgnoredUser(anArray.getAsString());
        }

        Hilda.getLogger().info("Ignored " + array.size() + " naughty users.");
    }

    if (this.channel != null) {
        this.channel
                .sendMessage(
                        "Hello! " + this.getHilda().getBot().getSelfUser().getName() + " has just started.")
                .queue();
    }
}

From source file:ch.jamiete.hilda.admin.commands.AdminConfigCommand.java

License:Apache License

@Override
public void execute(final Message message, final String[] args, final String label) {
    final Configuration config = this.hilda.getConfigurationManager().getConfiguration(this.plugin);

    if (args.length == 0) {
        this.usage(message, "<role/log>", label);
        return;//  w  ww  .  j a  v a 2 s .c om
    }

    if (args[0].equalsIgnoreCase("role")) {
        if (args.length == 1) { // Provide current value
            final JsonElement output = config.get().get("role");

            if (output == null) {
                this.reply(message, "There is no role currently set."); // Probably impossible to reach
            } else {
                final Role role = message.getGuild().getRoleById(output.getAsString());

                if (role == null) {
                    config.get().remove("role");
                    config.save();
                    this.reply(message, "The role specified no longer exists. I've removed it.");
                } else {
                    this.reply(message,
                            "I'm currently responding to " + role.getName() + " (" + role.getId() + ")");
                }
            }
        } else {
            if (message.getMentionedRoles().isEmpty()) {
                this.reply(message, "Please mention the role you want me to respond to.");
            } else {
                final Role role = message.getMentionedRoles().get(0);

                config.get().addProperty("role", role.getId());
                config.save();
                this.reply(message, "I'm now responding to " + role.getAsMention());
            }
        }
    }

    if (args[0].equalsIgnoreCase("log")) {
        if (args.length == 1) { // Provide current value
            final JsonElement output = config.get().get("log");

            if (output == null) {
                this.reply(message, "There is no log channel currently set."); // Probably impossible to reach
            } else {
                final TextChannel channel = message.getGuild().getTextChannelById(output.getAsString());

                if (channel == null) {
                    config.get().remove("log");
                    config.save();
                    this.reply(message, "The log channel specified no longer exists. I've removed it.");
                } else {
                    this.reply(message, "I'm currently logging to " + channel.getAsMention());
                }
            }
        } else {
            if (message.getMentionedChannels().isEmpty()) {
                this.reply(message, "Please mention the channel you want me to respond to.");
            } else {
                final TextChannel channel = message.getMentionedChannels().get(0);

                config.get().addProperty("log", channel.getId());
                config.save();
                this.reply(message, "I'm now logging to " + channel.getAsMention());
            }
        }
    }
}

From source file:ch.jamiete.hilda.configuration.Configuration.java

License:Apache License

public String getString(final String name, final String def) {
    final JsonElement ele = this.json.get(name);

    if (ele == null) {
        return def;
    }//from   w ww  .  j av  a2  s .  c om

    try {
        return ele.getAsString();
    } catch (final Exception e) {
        return def;
    }
}

From source file:ch.jamiete.hilda.music.commands.MusicAdminCommand.java

License:Apache License

@Override
public final void execute(final Message message, final String[] args, final String label) {
    final Configuration config = this.hilda.getConfigurationManager().getConfiguration(this.manager.getPlugin(),
            message.getGuild().getId());

    if (args.length == 0) {
        this.usage(message, "<output/lock>", label);
        return;//from   w w w .  j ava2s  .c  o m
    }

    if ("output".equalsIgnoreCase(args[0])) {
        if (args.length == 1) { // Provide current value
            final JsonElement output = config.get().get("output");

            if (output == null) {
                this.reply(message, "There is no output channel currently forced.");
            } else {
                final TextChannel channel = message.getGuild().getTextChannelById(output.getAsString());

                if (channel == null) {
                    config.get().remove("output");
                    config.save();
                    this.reply(message, "The output channel specified no longer exists. I've removed it.");
                } else {
                    this.reply(message, "I'm currently outputting into " + channel.getAsMention());
                }
            }
        } else {
            if (message.getMentionedChannels().isEmpty()) {
                this.reply(message, "Please mention the channel you want me to output into.");
            } else {
                final TextChannel channel = message.getMentionedChannels().get(0);

                config.get().addProperty("output", channel.getId());
                config.save();
                this.reply(message, "I'm now outputting into " + channel.getAsMention());
            }
        }
    }

    if ("lock".equalsIgnoreCase(args[0])) {
        if (args.length == 1) { // Provide current value
            final JsonElement output = config.get().get("lock");

            if (output == null) {
                this.reply(message, "There is no voice channel currently forced.");
            } else {
                final VoiceChannel channel = message.getGuild().getVoiceChannelById(output.getAsString());

                if (channel == null) {
                    config.get().remove("lock");
                    config.save();
                    this.reply(message, "The voice channel specified no longer exists. I've removed it.");
                } else {
                    this.reply(message, "I'm currently locked to " + channel.getName());
                }
            }
        } else {
            final List<VoiceChannel> channels = message.getGuild()
                    .getVoiceChannelsByName(Util.combineSplit(1, args, " "), true);

            if (channels.isEmpty()) {
                this.reply(message, "I couldn't find any channels matching that name.");
            } else {
                final VoiceChannel channel = channels.get(0);

                config.get().addProperty("lock", channel.getId());
                config.save();
                this.reply(message, "I'm now locked to " + channel.getName());
            }
        }
    }
}

From source file:ch.jamiete.hilda.music.commands.MusicPlayCommand.java

License:Apache License

@Override
public final void execute(final Message message, final String[] args, final String label) {
    final Member member = message.getGuild().getMember(message.getAuthor());

    if (args.length == 0) {
        this.usage(message, "<url/search query>", label);
        return;/* www  . j a  v  a  2  s.  c  o m*/
    }

    // User requirement logic
    if (!member.getVoiceState().inVoiceChannel()) {
        Hilda.getLogger().fine("Rejected command because user not in voice channel");
        this.reply(message, "You must be in a voice channel to queue music.");
        return;
    }

    final MusicServer server = this.manager.hasServer(message.getGuild())
            ? this.manager.getServer(message.getGuild())
            : this.manager.createServer(message.getGuild());

    if (server.getChannel() == null) {
        final JsonElement lock = server.getConfig().get().get("lock");

        if (lock != null) {
            final VoiceChannel req = message.getGuild().getVoiceChannelById(lock.getAsString());

            if ((req != null) && !member.getVoiceState().getChannel().equals(req)) {
                Hilda.getLogger().fine("Rejected command because user not in locked voice channel");
                this.reply(message, "You can only queue music in " + req.getName());
                return;
            }
        }

        server.setChannel(member.getVoiceState().getChannel()); // Join channel
    } else {
        if (server.getChannel() != member.getVoiceState().getChannel()) {
            Hilda.getLogger().fine("Rejected command because user not in same voice channel");
            this.reply(message, "You must be in the same voice channel as me to queue music.");
            return;
        }
    }

    // URL logic
    if ((args.length == 1) && args[0].toLowerCase().startsWith("http")) {
        Hilda.getLogger().info("Attempting to load URL " + args[0]);
        message.getChannel().sendTyping().queue();
        this.manager.getAudioPlayerManager().loadItemOrdered(server.getPlayer(), args[0],
                new LoadResults(server, message));
        return;
    }

    // Search logic
    final String search = Util.combineSplit(0, args, " ");
    Hilda.getLogger().info("Attempting to search YouTube for " + search);
    message.getChannel().sendTyping().queue();
    this.manager.getAudioPlayerManager().loadItemOrdered(server.getPlayer(), "ytsearch:" + search,
            new LoadResults(server, message, true));
}

From source file:ch.jamiete.hilda.music.MusicServer.java

License:Apache License

/**
 * Attempts to send a message. The bot will try the following channels in order: "bot", "bots", the default channel, the first channel that can be messaged.
 * The bot will pick the first of these that it can send a message to. If the bot cannot find any channels it will shutdown.
 * @param message The message to send//ww w.  j  a va  2s.  c  o  m
 */
public final void sendMessage(final String message) {
    TextChannel channel = null;

    final JsonElement output = this.config.get().get("output");

    if (output != null) {
        channel = this.guild.getTextChannelById(output.getAsString());
    }

    if (channel == null) {
        for (final TextChannel chan : this.guild.getTextChannels()) {
            if ("bot".equalsIgnoreCase(chan.getName()) && chan.canTalk()) {
                channel = chan;
            }

            if ("bots".equalsIgnoreCase(chan.getName()) && chan.canTalk()) {
                channel = chan;
            }
        }
    }

    if (channel == null) {
        if (this.guild.getDefaultChannel().canTalk()) {
            channel = this.guild.getDefaultChannel();
        } else {
            final Optional<TextChannel> chan = this.guild.getTextChannels().stream()
                    .filter(TextChannel::canTalk).findFirst();

            if (chan.isPresent()) {
                channel = chan.get();
            } else {
                Hilda.getLogger().severe("Couldn't find any channels to talk to in " + this.guild.getName()
                        + ' ' + this.guild.getId() + "; leaving...");
                this.shutdown();
                return;
            }
        }
    }

    Hilda.getLogger().fine("Sending a message; decided to use " + channel.getName() + "...");
    channel.sendMessage(Util.sanitise(message)).queue();
}

From source file:cheerPackage.JSONUtils.java

public static String getJsonAttributeValue(String rawJson, String attribute)
        throws MalformedJsonException, JsonSyntaxException {
    //just a single Json Object
    JsonParser parser = new JsonParser();
    JsonElement json = parser.parse(rawJson);
    if (json.isJsonObject()) {
        return json.getAsJsonObject().get(attribute).getAsString();
    } else if (json.isJsonPrimitive()) {
        return json.getAsString();
    } else {//from   w  ww  .jav a 2s  .co  m
        System.out.println(
                "This function only works on Json objects and primitives, use getValieFromArrayElement for arrays");
        return null;
    }
}

From source file:cheerPackage.JSONUtils.java

public static String getValueFromArrayElement(String jsonArrayString, String attribute, int index)
        throws MalformedJsonException, JsonSyntaxException {
    JsonParser parser = new JsonParser();
    JsonElement json = parser.parse(jsonArrayString);
    if (json.isJsonArray()) {
        JsonElement firstItem = json.getAsJsonArray().get(index);
        if (firstItem.isJsonPrimitive()) {
            return firstItem.getAsString();
        } else if (firstItem.isJsonObject()) {
            return firstItem.getAsJsonObject().get(attribute).getAsString();
        } else {//from ww  w  . j  a  va 2 s .  c o  m
            System.out.println(
                    "This function only goes in 1 level (from Array to Object in array, or primitive).");
            return null;
        }
    } else {
        System.out.println("This function only works on Json arrays.");
        return null;
    }
}