Example usage for com.google.gson JsonArray remove

List of usage examples for com.google.gson JsonArray remove

Introduction

In this page you can find the example usage for com.google.gson JsonArray remove.

Prototype

public JsonElement remove(int index) 

Source Link

Document

Removes the element at the specified position in this array.

Usage

From source file:arces.unibo.SEPA.commons.SPARQL.BindingsResults.java

License:Open Source License

public void remove(Bindings solution) {
    if (solution == null)
        return;//from www .j  av a2  s  .  c om
    JsonArray bindings = getBindingsArray();
    if (bindings == null)
        return;

    bindings.remove(solution.toJson());
}

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

License:Apache License

@Override
public void execute(final Message message, final String[] arguments, final String label) {
    if (arguments.length == 1 && arguments[0].equalsIgnoreCase("list")) {
        final List<String> strings = new ArrayList<>();

        for (String str : this.hilda.getAllowedServers()) {
            Guild guild = this.hilda.getBot().getGuildById(str);

            if (guild != null) {
                strings.add(this.name(guild));
            }/*www. ja  v  a 2 s .c o  m*/
        }

        if (strings.isEmpty()) {
            this.reply(message, "The whitelist function is not enabled!");
        } else {
            final MessageBuilder mb = new MessageBuilder();
            mb.append("I'm currently allowing ");

            if (strings.size() != this.hilda.getBot().getGuilds().size()) {
                mb.append("only ");
            }

            mb.append(strings.size()).append(strings.size() == 1 ? "server" : "servers").append(": ");
            mb.append(Util.getAsList(strings));
            mb.append(".");
            this.reply(message, mb.build());
        }

        return;
    }

    if (arguments.length == 0) {
        this.usage(message, "<id.../list>");
    }

    final AllowDirection direction = AllowDirection.valueOf(label.toUpperCase());
    final List<String> ids = new ArrayList<>();
    final List<String> success = new ArrayList<>();
    final List<String> fail = new ArrayList<>();

    for (final String arg : arguments) {
        Guild guild = this.hilda.getBot().getGuildById(arg);

        if (guild == null) {
            fail.add(arg);
        } else {
            ids.add(arg);
            success.add(this.name(guild));
        }
    }

    if (!success.isEmpty()) {
        final Configuration cfg = this.hilda.getConfigurationManager().getConfiguration(this.plugin,
                "allowedservers");
        JsonArray array = cfg.get().getAsJsonArray("servers");

        if (array == null) {
            array = new JsonArray();
        }

        for (final String id : ids) {
            if (direction == AllowDirection.ALLOW) {
                this.hilda.addAllowedServer(id);

                if (!array.contains(new JsonPrimitive(id))) {
                    array.add(id);
                }
            }

            if (direction == AllowDirection.DISALLOW) {
                this.hilda.removeAllowedServer(id);
                array.remove(new JsonPrimitive(id));
            }
        }

        cfg.get().add("servers", array);
        cfg.save();
    }

    final MessageBuilder mb = new MessageBuilder();

    mb.append("OK, ");

    if (!success.isEmpty()) {
        mb.append("I'm ").append(direction == AllowDirection.ALLOW ? "now" : "no longer").append(" allowing ");
        mb.append(Util.getAsList(success));
    }

    if (!fail.isEmpty()) {
        if (!success.isEmpty()) {
            mb.append(", however ");
        }

        mb.append("I couldn't find any servers matching ");
        mb.append(Util.getAsList(fail));
    }

    mb.append(".");

    mb.buildAll(SplitPolicy.SPACE).forEach(m -> message.getChannel().sendMessage(m).queue());
}

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

License:Apache License

@Override
public void execute(final Message message, final String[] arguments, final String label) {
    if (arguments.length == 1 && arguments[0].equalsIgnoreCase("list")) {
        final List<String> strings = this.hilda.getCommandManager().getIgnoredUsers();

        if (strings.isEmpty()) {
            this.reply(message, "I'm not ignoring any channels!");
        } else {/*from  w  ww  .  j ava2  s .  co  m*/
            final MessageBuilder mb = new MessageBuilder();
            mb.append("I'm currently ignoring ");
            mb.append(Util.getAsList(this.getPieces(strings)));
            mb.append(".");
            this.reply(message, mb.build());
        }

        return;
    }

    if (arguments.length == 0) {
        this.usage(message, "<@user.../id...>");
    }

    final IgnoreDirection direction = IgnoreDirection.valueOf(label.toUpperCase());
    final List<String> ids = new ArrayList<>();

    if (!message.getMentionedUsers().isEmpty()) {
        message.getMentionedUsers().forEach(u -> ids.add(u.getId()));
    }

    for (final String arg : arguments) {
        if (!arg.startsWith("<@")) {
            ids.add(arg);
        }
    }

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

    if (array == null) {
        array = new JsonArray();
    }

    for (final String id : ids) {
        if (direction == IgnoreDirection.IGNORE) {
            this.hilda.getCommandManager().addIgnoredUser(id);

            if (!array.contains(new JsonPrimitive(id))) {
                array.add(id);
            }
        }

        if (direction == IgnoreDirection.UNIGNORE) {
            this.hilda.getCommandManager().removeIgnoredUser(id);
            array.remove(new JsonPrimitive(id));
        }
    }

    cfg.get().add("users", array);
    cfg.save();

    final MessageBuilder mb = new MessageBuilder();

    mb.append("OK, I'm ").append(direction == IgnoreDirection.IGNORE ? "now" : "no longer")
            .append(" ignoring ");
    mb.append(Util.getAsList(this.getPieces(ids)));
    mb.append(".");

    mb.buildAll(SplitPolicy.SPACE).forEach(m -> message.getChannel().sendMessage(m).queue());
}

From source file:ch.jamiete.hilda.moderatortools.commands.IgnoreCommand.java

License:Apache License

@Override
public void execute(final Message message, final String[] arguments, final String label) {
    if (arguments.length == 1 && arguments[0].equalsIgnoreCase("list")) {
        final MessageBuilder mb = new MessageBuilder();
        final List<String> strings = this.hilda.getCommandManager().getIgnoredChannels();
        final List<TextChannel> ignored = new ArrayList<TextChannel>();

        for (final String s : strings) {
            final TextChannel c = message.getGuild().getTextChannelById(s);

            if (c != null) {
                ignored.add(c);//  w  w w. j a v  a 2  s .  c  om
            }
        }

        if (ignored.isEmpty()) {
            this.reply(message, "I'm not ignoring any channels!");
        } else {
            mb.append("I'm currently ignoring ");

            for (final TextChannel c : ignored) {
                mb.append(c.getAsMention());
                mb.append(", ");
            }

            mb.replaceLast(", ", "");
            mb.append(".");
            this.reply(message, mb.build());
        }

        return;
    }

    final IgnoreDirection direction = IgnoreDirection.valueOf(label.toUpperCase());
    final List<TextChannel> channels = new ArrayList<TextChannel>();

    if (arguments.length == 0) {
        channels.add(message.getTextChannel());
    }

    if (!message.getMentionedChannels().isEmpty()) {
        channels.addAll(message.getMentionedChannels());
    }

    final Configuration cfg = this.hilda.getConfigurationManager().getConfiguration(this.plugin,
            "ignore-" + message.getGuild().getId());
    JsonArray array = cfg.get().getAsJsonArray("channels");

    if (array == null) {
        array = new JsonArray();
    }

    for (final TextChannel channel : channels) {
        if (direction == IgnoreDirection.IGNORE) {
            this.hilda.getCommandManager().addIgnoredChannel(channel.getId());

            if (!array.contains(new JsonPrimitive(channel.getId()))) {
                array.add(channel.getId());
            }
        }

        if (direction == IgnoreDirection.UNIGNORE) {
            this.hilda.getCommandManager().removeIgnoredChannel(channel.getId());
            array.remove(new JsonPrimitive(channel.getId()));
        }
    }

    cfg.get().add("channels", array);
    cfg.save();

    final MessageBuilder mb = new MessageBuilder();

    mb.append("OK, I'm ").append(direction == IgnoreDirection.IGNORE ? "now" : "no longer")
            .append(" ignoring ");
    mb.append(Util.getChannelsAsString(channels));
    mb.append(".");

    mb.buildAll().forEach(m -> message.getChannel().sendMessage(m).queue());
}

From source file:com.exalttech.trex.ui.views.streams.binders.BuilderDataBinding.java

License:Apache License

public String serializeAsPacketModel() {

    JsonObject model = new JsonObject();
    model.add("protocols", new JsonArray());

    JsonObject fieldEngine = new JsonObject();
    fieldEngine.add("instructions", new JsonArray());
    fieldEngine.add("global_parameters", new JsonObject());
    model.add("field_engine", fieldEngine);

    Map<String, AddressDataBinding> l3Binds = new HashMap<>();

    l3Binds.put("Ether", macDB);
    boolean isIPv4 = protocolSelection.getIpv4Property().get();
    if (isIPv4) {
        l3Binds.put("IP", ipv4DB);
    }/*from   w  w  w  .  j  a va2  s  .  c  om*/

    l3Binds.entrySet().stream().forEach(entry -> {
        JsonObject proto = new JsonObject();
        String protoID = entry.getKey();
        proto.add("id", new JsonPrimitive(protoID));

        JsonArray fields = new JsonArray();

        AddressDataBinding binding = entry.getValue();
        String srcMode = entry.getValue().getDestination().getModeProperty().get();
        String dstMode = entry.getValue().getSource().getModeProperty().get();

        if (!MODE_TREX_CONFIG.equals(srcMode)) {
            fields.add(buildProtoField("src", binding.getSource().getAddressProperty().getValue()));
        }

        if (!MODE_TREX_CONFIG.equals(dstMode)) {
            fields.add(buildProtoField("dst", binding.getDestination().getAddressProperty().getValue()));
        }

        if (protoID.equals("Ether") && ethernetDB.getOverrideProperty().get()) {
            fields.add(buildProtoField("type", ethernetDB.getTypeProperty().getValue()));
        }
        proto.add("fields", fields);
        model.getAsJsonArray("protocols").add(proto);
        if (!MODE_FIXED.equals(binding.getSource().getModeProperty().get())
                && !MODE_TREX_CONFIG.equals(binding.getSource().getModeProperty().get())) {
            fieldEngine.getAsJsonArray("instructions")
                    .addAll(buildVMInstructions(protoID, "src", binding.getSource()));
        }
        if (!MODE_FIXED.equals(binding.getDestination().getModeProperty().get())
                && !MODE_TREX_CONFIG.equals(binding.getDestination().getModeProperty().get())) {
            fieldEngine.getAsJsonArray("instructions")
                    .addAll(buildVMInstructions(protoID, "dst", binding.getDestination()));
        }

    });

    boolean isVLAN = protocolSelection.getTaggedVlanProperty().get();
    String pktLenName = "pkt_len";
    String frameLenghtType = protocolSelection.getFrameLengthType();
    boolean pktSizeChanged = !frameLenghtType.equals("Fixed");
    if (pktSizeChanged) {
        LinkedHashMap<String, String> instructionParam = new LinkedHashMap<>();
        String operation = PacketBuilderHelper.getOperationFromType(frameLenghtType);
        Integer minLength = Integer.valueOf(protocolSelection.getMinLength()) - 4;
        Integer maxLength = Integer.valueOf(protocolSelection.getMaxLength()) - 4;

        instructionParam.put("init_value", minLength.toString());
        instructionParam.put("max_value", maxLength.toString());
        instructionParam.put("min_value", minLength.toString());

        instructionParam.put("name", pktLenName);
        instructionParam.put("op", operation);
        instructionParam.put("size", "2");
        instructionParam.put("step", "1");
        fieldEngine.getAsJsonArray("instructions").add(buildInstruction("STLVmFlowVar", instructionParam));

        instructionParam.clear();
        instructionParam.put("fv_name", pktLenName);
        fieldEngine.getAsJsonArray("instructions").add(buildInstruction("STLVmTrimPktSize", instructionParam));

        instructionParam.clear();
        instructionParam.put("add_val", isVLAN ? "-18" : "-14");
        instructionParam.put("is_big", "true");
        instructionParam.put("fv_name", pktLenName);
        instructionParam.put("pkt_offset", isVLAN ? "20" : "16");
        fieldEngine.getAsJsonArray("instructions").add(buildInstruction("STLVmWrFlowVar", instructionParam));
    }

    if (isVLAN) {
        JsonObject dot1QProto = new JsonObject();
        dot1QProto.add("id", new JsonPrimitive("Dot1Q"));
        Map<String, String> fieldsMap = new HashMap<>();

        fieldsMap.put("prio", vlanDB.getPriorityProperty().getValue());
        fieldsMap.put("id", vlanDB.getCfiProperty().getValue());
        fieldsMap.put("vlan", vlanDB.getVIdProperty().getValue());

        dot1QProto.add("fields", buildProtoFieldsFromMap(fieldsMap));

        JsonArray protocols = model.getAsJsonArray("protocols");
        if (protocols.size() == 2) {
            JsonElement ipv4 = protocols.get(1);
            protocols.set(1, dot1QProto);
            protocols.add(ipv4);
        } else {
            model.getAsJsonArray("protocols").add(dot1QProto);
        }

        if (vlanDB.getOverrideTPIdProperty().getValue()) {
            JsonArray etherFields = ((JsonObject) model.getAsJsonArray("protocols").get(0)).get("fields")
                    .getAsJsonArray();
            if (etherFields.size() == 3) {
                etherFields.remove(2);
            }
            etherFields.add(buildProtoField("type", vlanDB.getTpIdProperty().getValue()));
        }
    }

    boolean isTCP = protocolSelection.getTcpProperty().get();
    if (isTCP) {
        JsonObject tcpProto = new JsonObject();
        tcpProto.add("id", new JsonPrimitive("TCP"));

        Map<String, String> fieldsMap = new HashMap<>();
        fieldsMap.put("sport", tcpProtocolDB.getSrcPortProperty().getValue());
        fieldsMap.put("dport", tcpProtocolDB.getDstPortProperty().getValue());
        fieldsMap.put("chksum", "0x" + tcpProtocolDB.getChecksumProperty().getValue());
        fieldsMap.put("seq", tcpProtocolDB.getSequenceNumberProperty().getValue());
        fieldsMap.put("urgptr", tcpProtocolDB.getUrgentPointerProperty().getValue());
        fieldsMap.put("ack", tcpProtocolDB.getAckNumberProperty().getValue());

        int tcp_flags = 0;
        if (tcpProtocolDB.getUrgProperty().get()) {
            tcp_flags = tcp_flags | (1 << 5);
        }
        if (tcpProtocolDB.getAckProperty().get()) {
            tcp_flags = tcp_flags | (1 << 4);
        }
        if (tcpProtocolDB.getPshProperty().get()) {
            tcp_flags = tcp_flags | (1 << 3);
        }
        if (tcpProtocolDB.getRstProperty().get()) {
            tcp_flags = tcp_flags | (1 << 2);
        }
        if (tcpProtocolDB.getSynProperty().get()) {
            tcp_flags = tcp_flags | (1 << 1);
        }
        if (tcpProtocolDB.getFinProperty().get()) {
            tcp_flags = tcp_flags | 1;
        }
        fieldsMap.put("flags", String.valueOf(tcp_flags));

        tcpProto.add("fields", buildProtoFieldsFromMap(fieldsMap));
        model.getAsJsonArray("protocols").add(tcpProto);
    }

    // Field Engine instructions
    String cache_size = "5000";
    if ("Enable".equals(advancedPropertiesDB.getCacheSizeTypeProperty().getValue())) {
        cache_size = advancedPropertiesDB.getCacheValueProperty().getValue();
    }
    fieldEngine.getAsJsonObject("global_parameters").add("cache_size", new JsonPrimitive(cache_size));

    boolean isUDP = protocolSelection.getUdpProperty().get();
    if (isUDP) {
        JsonObject udpProto = new JsonObject();
        udpProto.add("id", new JsonPrimitive("UDP"));

        Map<String, String> fieldsMap = new HashMap<>();
        fieldsMap.put("sport", udpProtocolDB.getSrcPortProperty().getValue());
        fieldsMap.put("dport", udpProtocolDB.getDstPortProperty().getValue());
        fieldsMap.put("len", udpProtocolDB.getLengthProperty().getValue());

        udpProto.add("fields", buildProtoFieldsFromMap(fieldsMap));
        model.getAsJsonArray("protocols").add(udpProto);

        if (pktSizeChanged) {
            LinkedHashMap<String, String> instructionParam = new LinkedHashMap<>();
            instructionParam.put("add_val", isVLAN ? "-38" : "-34");
            instructionParam.put("is_big", "true");
            instructionParam.put("fv_name", pktLenName);
            instructionParam.put("pkt_offset", isVLAN ? "42" : "38");
            fieldEngine.getAsJsonArray("instructions")
                    .add(buildInstruction("STLVmWrFlowVar", instructionParam));
        }
    }

    if (ipv4DB.hasInstructions() || pktSizeChanged) {
        Map<String, String> flowWrVarParameters = new HashMap<>();
        flowWrVarParameters.put("offset", "IP");
        fieldEngine.getAsJsonArray("instructions").add(buildInstruction("STLVmFixIpv4", flowWrVarParameters));
    }

    return model.toString();
}

From source file:com.flipkart.android.proteus.toolbox.Utils.java

License:Apache License

public static JsonElement merge(JsonElement oldJson, JsonElement newJson, boolean useCopy, Gson gson) {

    JsonElement newDataElement;/*from   w ww . ja  va  2  s  .  c  om*/
    JsonArray oldArray;
    JsonArray newArray;
    JsonElement oldArrayItem;
    JsonElement newArrayItem;
    JsonObject oldObject;

    if (oldJson == null || oldJson.isJsonNull()) {
        return useCopy ? gson.fromJson(newJson, JsonElement.class) : newJson;
    }

    if (newJson == null || newJson.isJsonNull()) {
        newJson = JsonNull.INSTANCE;
        return newJson;
    }

    if (newJson.isJsonPrimitive()) {
        JsonPrimitive value;
        if (!useCopy) {
            return newJson;
        }
        if (newJson.getAsJsonPrimitive().isBoolean()) {
            value = new JsonPrimitive(newJson.getAsBoolean());
        } else if (newJson.getAsJsonPrimitive().isNumber()) {
            value = new JsonPrimitive(newJson.getAsNumber());
        } else if (newJson.getAsJsonPrimitive().isString()) {
            value = new JsonPrimitive(newJson.getAsString());
        } else {
            value = newJson.getAsJsonPrimitive();
        }
        return value;
    }

    if (newJson.isJsonArray()) {
        if (!oldJson.isJsonArray()) {
            return useCopy ? gson.fromJson(newJson, JsonArray.class) : newJson;
        } else {
            oldArray = oldJson.getAsJsonArray();
            newArray = newJson.getAsJsonArray();

            if (oldArray.size() > newArray.size()) {
                while (oldArray.size() > newArray.size()) {
                    oldArray.remove(oldArray.size() - 1);
                }
            }

            for (int index = 0; index < newArray.size(); index++) {
                if (index < oldArray.size()) {
                    oldArrayItem = oldArray.get(index);
                    newArrayItem = newArray.get(index);
                    oldArray.set(index, merge(oldArrayItem, newArrayItem, useCopy, gson));
                } else {
                    oldArray.add(newArray.get(index));
                }
            }
        }
    } else if (newJson.isJsonObject()) {
        if (!oldJson.isJsonObject()) {
            return useCopy ? gson.fromJson(newJson, JsonObject.class) : newJson;
        } else {
            oldObject = oldJson.getAsJsonObject();
            for (Map.Entry<String, JsonElement> entry : newJson.getAsJsonObject().entrySet()) {
                newDataElement = merge(oldObject.get(entry.getKey()), entry.getValue(), useCopy, gson);
                oldObject.add(entry.getKey(), newDataElement);
            }
        }
    } else {
        return useCopy ? gson.fromJson(newJson, JsonElement.class) : newJson;
    }

    return oldJson;
}

From source file:com.ibm.streamsx.topology.generator.spl.GraphUtilities.java

License:Open Source License

static void removeOperators(Collection<JsonObject> operators, JsonObject graph) {
    for (JsonObject iso : operators) {

        // Get parents and children of operator
        Set<JsonObject> operatorParents = getUpstream(iso, graph);
        Set<JsonObject> operatorChildren = getDownstream(iso, graph);

        JsonArray operatorOutputs = array(iso, "outputs");

        // Get the output name of the operator
        String operatorOutName = "";
        if (operatorOutputs != null) {
            JsonObject operatorFirstOutput = operatorOutputs.get(0).getAsJsonObject();
            if (operatorFirstOutput != null) {
                operatorOutName = jstring(operatorFirstOutput, "name");
            }/*from  w  w  w  .j ava2  s  .  c  o  m*/
        }

        // Also get input names
        List<String> operatorInNames = new ArrayList<>();
        inputs(iso, input -> operatorInNames.add(jstring(input, "name")));

        // Respectively, the names of the child and parent input and
        // output ports connected to the operator.
        List<String> childInputPortNames = new ArrayList<>();
        List<String> parentOutputPortNames = new ArrayList<>();

        // References to the list of connections for the parent and child
        // output and input ports that are connected to the $isolate$
        // operator.
        List<JsonArray> childConnections = new ArrayList<>();
        List<JsonArray> parentConnections = new ArrayList<>();

        // Get names of children's input ports that are connected to the
        // operator;
        for (JsonObject child : operatorChildren) {
            JsonArray inputs = child.get("inputs").getAsJsonArray();
            for (JsonElement inputObj : inputs) {
                JsonObject input = inputObj.getAsJsonObject();
                JsonArray connections = input.get("connections").getAsJsonArray();
                for (JsonElement connectionObj : connections) {
                    String connection = connectionObj.getAsString();
                    if (connection.equals(operatorOutName)) {
                        childInputPortNames.add(jstring(input, "name"));
                        childConnections.add(connections);
                        connections.remove(connectionObj);
                        break;
                    }
                }
            }
        }

        // Get names of parent's output ports that are connected to the
        // $Isolate$ operator;
        for (JsonObject parent : operatorParents) {
            JsonArray outputs = parent.get("outputs").getAsJsonArray();
            for (JsonElement outputObj : outputs) {
                JsonObject output = outputObj.getAsJsonObject();
                JsonArray connections = output.get("connections").getAsJsonArray();
                for (JsonElement connectionObj : connections) {
                    String connection = connectionObj.getAsString();
                    if (operatorInNames.contains(connection)) {
                        parentOutputPortNames.add(jstring(output, "name"));
                        parentConnections.add(connections);
                        connections.remove(connectionObj);
                        break;
                    }
                }
            }
        }

        // Connect child to parents
        for (JsonArray childConnection : childConnections) {
            for (String name : parentOutputPortNames)
                childConnection.add(new JsonPrimitive(name));
        }

        // Connect parent to children
        for (JsonArray parentConnection : parentConnections) {
            for (String name : childInputPortNames)
                parentConnection.add(new JsonPrimitive(name));
        }
        JsonArray ops = graph.get("operators").getAsJsonArray();
        ops.remove(iso);
    }
}

From source file:com.itametis.jsonconverter.pathstrategy.flattener.JsonArrayFlattener.java

License:Open Source License

@Override
protected void empty(JsonArray element) {
    LOGGER.debug("emptying json array {}", element.toString());
    List<JsonElement> toRemove = new ArrayList<>();
    for (int i = 0; i < element.size(); i++) {
        toRemove.add(element.get(i));//  www . j a  v  a 2  s  . c  o  m
    }
    for (JsonElement elementToRemove : toRemove) {
        element.remove(elementToRemove);
    }
}

From source file:com.jayway.jsonpath.internal.spi.json.GsonJsonProvider.java

License:Apache License

@SuppressWarnings("unchecked")
public void removeProperty(Object obj, Object key) {
    if (isMap(obj))
        toJsonObject(obj).remove(key.toString());
    else {//  w  ww  . j av  a  2  s .com
        JsonArray array = toJsonArray(obj);
        int index = key instanceof Integer ? (Integer) key : Integer.parseInt(key.toString());
        array.remove(index);
    }
}

From source file:com.jayway.jsonpath.spi.json.GsonJsonProvider.java

License:Apache License

@SuppressWarnings("unchecked")
public void removeProperty(final Object obj, final Object key) {
    if (isMap(obj)) {
        toJsonObject(obj).remove(key.toString());
    } else {// w w  w . j av a  2  s. c o  m
        JsonArray array = toJsonArray(obj);
        int index = key instanceof Integer ? (Integer) key : Integer.parseInt(key.toString());
        array.remove(index);
    }
}