Example usage for com.google.gson JsonObject has

List of usage examples for com.google.gson JsonObject has

Introduction

In this page you can find the example usage for com.google.gson JsonObject has.

Prototype

public boolean has(String memberName) 

Source Link

Document

Convenience method to check if a member with the specified name is present in this object.

Usage

From source file:ccm.pay2spawn.types.EntityType.java

License:Open Source License

@Override
public String replaceInTemplate(String id, JsonObject jsonObject) {
    switch (id) {
    case "entity":
        StringBuilder sb = new StringBuilder();
        sb.append(jsonObject.get(ENTITYNAME_KEY).getAsString().replace("STRING:", ""));
        while (jsonObject.has(RIDING_KEY)) {
            jsonObject = jsonObject.getAsJsonObject(RIDING_KEY);
            sb.append(" riding a ").append(jsonObject.get(ENTITYNAME_KEY).getAsString().replace("STRING:", ""));
        }//from www.jav a  2s.c o m
        return sb.toString();
    }
    return id;
}

From source file:ccm.pay2spawn.types.guis.HelperGuiBase.java

License:Open Source License

public String readValue(String key, JsonObject jsonObject) {
    if (jsonObject == null || !jsonObject.has(key))
        return "";
    String string = jsonObject.get(key).getAsString();
    return string.substring(string.indexOf(":") + 1);
}

From source file:ccm.pay2spawn.types.PlayerModificationType.java

License:Open Source License

@Override
public String replaceInTemplate(String id, JsonObject jsonObject) {
    switch (id) {
    case "type":
        return Type.values()[Integer.parseInt(jsonObject.get(TYPE_KEY).getAsString().split(":", 2)[1])].name()
                .toLowerCase();/*from  ww  w. j av a2  s  .c om*/
    case "operation":
        switch (Integer.parseInt(jsonObject.get(OPERATION_KEY).getAsString().split(":", 2)[1])) {
        case ADD:
            return "adding";
        case SUBTRACT:
            return "subtracting";
        case SET:
            return "setting";
        case ENABLE:
            return "enabling it" + (jsonObject.has(AMOUNT_KEY) ? " for" : "");
        case DISABLE:
            return "disabling it" + (jsonObject.has(AMOUNT_KEY) ? " for" : "");
        }
    case "amount":
        if (jsonObject.has(AMOUNT_KEY))
            return NUMBER_FORMATTER
                    .format(Float.parseFloat(jsonObject.get(OPERATION_KEY).getAsString().split(":", 2)[1]));
        else
            return "";
    }
    return id;
}

From source file:ccm.pay2spawn.util.Reward.java

License:Open Source License

public String getHTML() throws IOException {
    StringBuilder sb = new StringBuilder();
    for (JsonElement element : rewards) {
        JsonObject object = element.getAsJsonObject();
        if (object.has(CUSTOMHTML) && !Strings.isNullOrEmpty(object.get(CUSTOMHTML).getAsString()))
            sb.append(object.get(CUSTOMHTML).getAsString());
        else//from   w ww . j av  a 2  s.co  m
            sb.append(TypeRegistry.getByName(object.get("type").getAsString())
                    .getHTML(object.getAsJsonObject("data")));
    }
    return sb.toString();
}

From source file:cf.adriantodt.David.modules.cmds.FeedCmd.java

License:LGPL

@PostReady
private static void lazyLoad() {
    logger.trace("Loading...");
    PushCmd.registerDynamicTypes(() -> ALL_TYPES, "feeds");

    DBModule.onDB(r -> r.table("feeds")).run().cursorExpected().forEach(json -> {
        JsonObject feed = json.getAsJsonObject();
        Subscription s = new Subscription(feed.get("pushName").getAsString(),
                newURL(EncodingUtil.decodeURIComponent(feed.get("url").getAsString())),
                feed.get("id").getAsString());

        if (feed.has("lastHashCode") && ConfigUtils.isJsonNumber(feed.get("lastHashCode")))
            s.setLastHashCode(feed.get("lastHashCode").getAsInt());
    });//from w  ww . ja  v a2s. c om

    i = 1;
    logger.trace("k");

    TaskManager.startAsyncTask("Feed Loop", FeedCmd::loop, 5);
}

From source file:cf.adriantodt.David.modules.db.I18nModule.java

License:LGPL

@PostReady
private static void load() {
    localizeLocal("botname", jda.getSelfUser().getName());
    localizeLocal("mention", jda.getSelfUser().getAsMention());

    JsonObject mainFile = new JsonParser().parse(i18nMain).getAsJsonObject();
    mainFile.entrySet().forEach(entry -> {
        //Before Load, Parse Contents
        JsonObject def = entry.getValue().getAsJsonObject();
        if (def.has("parent"))
            setParent(entry.getKey(), def.get("parent").getAsString());

        String resource = manager.get(entry.getKey() + ".json");
        if (resource == null)
            return;

        loadFile(entry.getKey(), new JsonParser().parse(resource));
    });/*from w  ww. jav  a2  s  .c om*/
}

From source file:cf.adriantodt.David.modules.db.I18nModule.java

License:LGPL

private static void loadFile(String lang, JsonElement src) {
    if (!src.isJsonObject())
        return;//w ww .j  a  v  a 2 s. c  o  m
    JsonObject file = src.getAsJsonObject();

    List<Exception> post = new ArrayList<>();

    try {
        if (file.has("translations")) {
            loadTranslation(lang, "", file.get("translations"), post);
        }
    } catch (Exception e) {
        post.add(e);
    }

    try {
        if (file.has("commands")) {
            JsonElement metaSrc = file.get("meta");

            JsonObject meta = metaSrc.isJsonObject() ? metaSrc.getAsJsonObject() : null;

            file.get("commands").getAsJsonObject().entrySet()
                    .forEach(entry -> loadCommand(lang, entry.getKey(), entry.getValue(), meta, post));
        }
    } catch (Exception e) {
        post.add(e);
    }

    if (post.size() > 0) {
        logger().info("Errors occurred while loading I18nModule:");
        post.forEach(e -> logger().error(e));
    }
}

From source file:cf.adriantodt.David.modules.db.I18nModule.java

License:LGPL

private static void loadCommand(String lang, String name, JsonElement src, JsonObject metadata,
        List<Exception> post) {
    logger().trace(lang + " - " + name + " - " + src.toString());
    if (!src.isJsonObject())
        return;/*  w  w w.  j  av  a 2  s .com*/
    JsonObject cmd = src.getAsJsonObject();
    try {
        if (cmd.has("desc") || cmd.has("params") || cmd.has("info")) {
            String desc = cmd.has("desc") ? cmd.get("desc").getAsString()
                    : metadata.get("noDesc").getAsString();
            String params = cmd.has("params") ? cmd.get("params").getAsString()
                    : metadata.get("noParams").getAsString();
            String info = cmd.has("info") ? "\n  " + cmd.get("info").getAsString().replace("\n", "\n  ") : "";
            localize(lang, name + ".usage",
                    desc + "\n" + metadata.get("params").getAsString() + ": " + params + info);
        }
    } catch (Exception e) {
        post.add(e);
    }

    try {
        if (cmd.has("translations")) {
            loadTranslation(lang, name + ".", cmd.get("translations"), post);
        }
    } catch (Exception e) {
        post.add(e);
    }

    try {
        if (cmd.has("subs") && cmd.get("subs").isJsonObject()) {
            cmd.get("subs").getAsJsonObject().entrySet().forEach(
                    entry -> loadCommand(lang, name + "." + entry.getKey(), entry.getValue(), metadata, post));
        }
    } catch (Exception e) {
        post.add(e);
    }
}

From source file:ch.cyberduck.core.sds.SDSExceptionMappingService.java

License:Open Source License

@Override
public BackgroundException map(final ApiException failure) {
    for (Throwable cause : ExceptionUtils.getThrowableList(failure)) {
        if (cause instanceof SocketException) {
            // Map Connection has been shutdown: javax.net.ssl.SSLException: java.net.SocketException: Broken pipe
            return new DefaultSocketExceptionMappingService().map((SocketException) cause);
        }/*  w  ww  .  ja va 2s .  c o m*/
        if (cause instanceof HttpResponseException) {
            return new HttpResponseExceptionMappingService().map((HttpResponseException) cause);
        }
        if (cause instanceof IOException) {
            return new DefaultIOExceptionMappingService().map((IOException) cause);
        }
    }
    final StringBuilder buffer = new StringBuilder();
    if (null != failure.getResponseBody()) {
        final JsonParser parser = new JsonParser();
        try {
            final JsonObject json = parser.parse(new StringReader(failure.getResponseBody())).getAsJsonObject();
            if (json.has("errorCode")) {
                if (json.get("errorCode").isJsonPrimitive()) {
                    final int errorCode = json.getAsJsonPrimitive("errorCode").getAsInt();
                    if (log.isDebugEnabled()) {
                        log.debug(String.format("Failure with errorCode %s", errorCode));
                    }
                    final String key = String.format("Error %d", errorCode);
                    final String localized = LocaleFactory.get().localize(key, "SDS");
                    this.append(buffer, localized);
                    if (StringUtils.equals(localized, key)) {
                        log.warn(String.format("Missing user message for error code %d", errorCode));
                        if (json.has("debugInfo")) {
                            if (json.get("debugInfo").isJsonPrimitive()) {
                                this.append(buffer, json.getAsJsonPrimitive("debugInfo").getAsString());
                            }
                        }
                    }
                    switch (failure.getCode()) {
                    case HttpStatus.SC_NOT_FOUND:
                        switch (errorCode) {
                        case -70501:
                            // [-70501] User not found
                            return new AccessDeniedException(buffer.toString(), failure);
                        case -40761:
                            // [-40761] Filekey not found for encrypted file
                            return new AccessDeniedException(buffer.toString(), failure);
                        }
                        break;
                    case HttpStatus.SC_PRECONDITION_FAILED:
                        switch (errorCode) {
                        case -10108:
                            // [-10108] Radius Access-Challenge required.
                            if (json.has("replyMessage")) {
                                if (json.get("replyMessage").isJsonPrimitive()) {
                                    final JsonPrimitive replyMessage = json.getAsJsonPrimitive("replyMessage");
                                    if (log.isDebugEnabled()) {
                                        log.debug(String.format("Failure with replyMessage %s", replyMessage));
                                    }
                                    buffer.append(replyMessage.getAsString());
                                }
                            }
                            return new PartialLoginFailureException(buffer.toString(), failure);
                        }
                        break;
                    case HttpStatus.SC_UNAUTHORIZED:
                        switch (errorCode) {
                        case -10012:
                            // [-10012] Wrong token.
                            return new ExpiredTokenException(buffer.toString(), failure);
                        }
                        break;
                    }
                }
            } else {
                switch (failure.getCode()) {
                case HttpStatus.SC_INTERNAL_SERVER_ERROR:
                    break;
                default:
                    if (json.has("debugInfo")) {
                        log.warn(String.format("Missing error code for failure %s", json));
                        if (json.get("debugInfo").isJsonPrimitive()) {
                            this.append(buffer, json.getAsJsonPrimitive("debugInfo").getAsString());
                        }
                    }
                }
            }
        } catch (JsonParseException e) {
            // Ignore
            this.append(buffer, failure.getMessage());
        }
    }
    switch (failure.getCode()) {
    case HttpStatus.SC_PRECONDITION_FAILED:
        // [-10103] EULA must be accepted
        // [-10104] Password must be changed
        // [-10106] Username must be changed
        return new LoginFailureException(buffer.toString(), failure);
    }
    return new HttpResponseExceptionMappingService().map(failure, buffer, failure.getCode());
}

From source file:ch.ethz.inf.vs.hypermedia.corehal.block.CoREHalResourceFuture.java

License:Open Source License

@Override
public V deserialize(String text) throws Exception {
    JsonObject jsonobj = getGson().fromJson(text, JsonObject.class);
    boolean hasDecoupled = jsonobj.has("_decoupled") && jsonobj.get("_decoupled").isJsonObject()
            && jsonobj.get("_decoupled").getAsJsonObject().entrySet().size() > 0;

    Class<V> type = hasDecoupled ? createProxyClass(getType()) : getType();
    V item = getGson().fromJson(jsonobj, type);
    item.setJson(jsonobj);//w  w w.  j ava 2  s .c  om
    if (hasDecoupled) {
        MethodHandler handler = (self, overridden, forwarder, args) -> {
            String methodName = overridden.getName();
            if (methodName.equals("decoupledLoader")) {
                args[1] = getUrl();
            }
            if ((!methodName.startsWith("get") && !methodName.startsWith("set"))
                    || methodName.equals("getDecoupled")) {
                return forwarder.invoke(self, args);
            }
            // Intercept call to the getter function getter access
            String itemname = methodName.substring(3);
            if (methodName.equals("get") || methodName.equals("set")) {
                itemname = (String) args[0];
            }
            itemname = itemname.substring(0, 1).toLowerCase() + itemname.substring(1);
            if (methodName.startsWith("get")) {
                if (item.getDecoupled() != null && item.getDecoupled().containsKey(itemname)) {
                    return item.loadDecoupled(itemname, getUrl());
                }
            }
            Object invoke = forwarder.invoke(self, args);
            if (methodName.startsWith("set")) {
                item.removeDecoupled(itemname);
            }
            return invoke;
        };
        ((ProxyObject) item).setHandler(handler);
    }
    return item;
}