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:br.unicamp.cst.bindings.soar.SOARPlugin.java

License:Open Source License

public void addBranchToJson(String newBranch, JsonObject json, double value) {
    String[] newNodes = newBranch.split("\\.");
    JsonObject temp;// = new JsonObject();

    if (newNodes.length > 1) {
        if (json.has(newNodes[0])) {
            addBranchToJson(newBranch.substring(newNodes[0].length() + 1), json.getAsJsonObject(newNodes[0]),
                    value);//www .jav a2  s  .  c  o m
        } else {
            temp = createJsonFromString(newBranch.substring(newNodes[0].length() + 1), value);
            json.add(newNodes[0], temp);
        }
    } else {
        json.addProperty(newNodes[0], value);
    }
}

From source file:br.unicamp.cst.bindings.soar.SOARPlugin.java

License:Open Source License

public void addBranchToJson(String newBranch, JsonObject json, String value) {
    String[] newNodes = newBranch.split("\\.");
    JsonObject temp;// = new JsonObject();

    if (newNodes.length > 1) {
        if (json.has(newNodes[0])) {
            addBranchToJson(newBranch.substring(newNodes[0].length() + 1), json.getAsJsonObject(newNodes[0]),
                    value);/* w w  w  .  jav a  2  s. co  m*/
        } else {
            temp = createJsonFromString(newBranch.substring(newNodes[0].length() + 1), value);
            json.add(newNodes[0], temp);
        }
    } else {
        json.addProperty(newNodes[0], value);
    }
}

From source file:br.unicamp.cst.bindings.soar.SOARPlugin.java

License:Open Source License

public void addBranchToJson(String newBranch, JsonObject json, JsonObject value) {
    String[] newNodes = newBranch.split("\\.");
    JsonObject temp;// = new JsonObject();

    if (newNodes.length > 1) {
        if (json.has(newNodes[0])) {
            addBranchToJson(newBranch.substring(newNodes[0].length() + 1), json.getAsJsonObject(newNodes[0]),
                    value);// w  w w.jav a 2 s  .  com
        } else {
            temp = createJsonFromString(newBranch.substring(newNodes[0].length() + 1), value);
            json.add(newNodes[0], temp);
        }
    } else {
        json.add(newNodes[0], value);
    }
}

From source file:br.unicamp.cst.bindings.soar.SOARPlugin.java

License:Open Source License

public void removeBranchFromJson(String pathToOldBranch, JsonObject json) {
    String[] oldNodes = pathToOldBranch.split("\\.");
    if (oldNodes.length > 1) {
        if (json.has(oldNodes[0])) {
            removeBranchFromJson(pathToOldBranch.substring(oldNodes[0].length() + 1),
                    json.getAsJsonObject(oldNodes[0]));
        }// w  w  w.j a v a  2 s  .co  m
    } else {
        json.remove(oldNodes[0]);
    }
}

From source file:brooklyn.entity.monitoring.zabbix.ZabbixFeed.java

License:Apache License

@Override
protected void preStart() {
    final Supplier<URI> baseUriProvider = getConfig(BASE_URI_PROVIDER);
    final Function<? super EntityLocal, String> uniqueHostnameGenerator = getConfig(UNIQUE_HOSTNAME_GENERATOR);
    final Integer groupId = getConfig(GROUP_ID);
    final Integer templateId = getConfig(TEMPLATE_ID);
    final Set<ZabbixPollConfig<?>> polls = getConfig(POLLS);

    log.info("starting zabbix feed for {}", entity);

    // TODO if supplier returns null, we may wish to defer initialization until url available?
    // TODO for https should we really trust all?
    final HttpClient httpClient = HttpTool.httpClientBuilder().trustAll()
            .clientConnectionManager(new ThreadSafeClientConnManager())
            .reuseStrategy(new NoConnectionReuseStrategy()).uri(baseUriProvider.get()).build();

    // Registration job, calls Zabbix host.create API
    final Callable<HttpToolResponse> registerJob = new Callable<HttpToolResponse>() {
        @Override//from   ww w  . j a  v  a 2 s  .  com
        public HttpToolResponse call() throws Exception {
            if (!registered.get()) {
                // Find the first machine, if available
                Optional<Location> location = Iterables.tryFind(entity.getLocations(),
                        Predicates.instanceOf(MachineLocation.class));
                if (!location.isPresent()) {
                    return null; // Do nothing until location is present
                }
                MachineLocation machine = (MachineLocation) location.get();

                String host = uniqueHostnameGenerator.apply(entity);

                // Select address and port using port-forwarding if available
                String address = entity.getAttribute(Attributes.ADDRESS);
                Integer port = entity.getAttribute(ZabbixMonitored.ZABBIX_AGENT_PORT);
                if (machine instanceof SupportsPortForwarding) {
                    Cidr management = entity.getConfig(BrooklynAccessUtils.MANAGEMENT_ACCESS_CIDR);
                    HostAndPort forwarded = ((SupportsPortForwarding) machine).getSocketEndpointFor(management,
                            port);
                    address = forwarded.getHostText();
                    port = forwarded.getPort();
                }

                // Fill in the JSON template and POST it
                byte[] body = JSON_HOST_CREATE
                        .replace("{{token}}",
                                entity.getConfig(ZabbixMonitored.ZABBIX_SERVER)
                                        .getAttribute(ZabbixServer.ZABBIX_TOKEN))
                        .replace("{{host}}", host).replace("{{ip}}", address)
                        .replace("{{port}}", Integer.toString(port))
                        .replace("{{groupId}}", Integer.toString(groupId))
                        .replace("{{templateId}}", Integer.toString(templateId))
                        .replace("{{id}}", Integer.toString(id.incrementAndGet())).getBytes();

                return HttpTool.httpPost(httpClient, baseUriProvider.get(),
                        ImmutableMap.of("Content-Type", "application/json"), body);
            }
            return null;
        }
    };

    // The handler for the registration job
    PollHandler<? super HttpToolResponse> registrationHandler = new PollHandler<HttpToolResponse>() {
        @Override
        public void onSuccess(HttpToolResponse val) {
            if (registered.get() || val == null) {
                return; // Skip if we are registered already or no data from job
            }
            JsonObject response = HttpValueFunctions.jsonContents().apply(val).getAsJsonObject();
            if (response.has("error")) {
                // Parse the JSON error object and log the message
                JsonObject error = response.get("error").getAsJsonObject();
                String message = error.get("message").getAsString();
                String data = error.get("data").getAsString();
                log.warn("zabbix failed registering host - {}: {}", message, data);
            } else if (response.has("result")) {
                // Parse the JSON result object and save the hostId
                JsonObject result = response.get("result").getAsJsonObject();
                String hostId = result.get("hostids").getAsJsonArray().get(0).getAsString();
                // Update the registered status if not set
                if (registered.compareAndSet(false, true)) {
                    entity.setAttribute(ZabbixMonitored.ZABBIX_AGENT_HOSTID, hostId);
                    log.info("zabbix registered host as id {}", hostId);
                }
            } else {
                throw new IllegalStateException(String
                        .format("zabbix host registration returned invalid result: %s", response.toString()));
            }
        }

        @Override
        public boolean checkSuccess(HttpToolResponse val) {
            return (val.getResponseCode() == 200);
        }

        @Override
        public void onFailure(HttpToolResponse val) {
            log.warn("zabbix sever returned failure code: {}", val.getResponseCode());
        }

        @Override
        public void onException(Exception exception) {
            log.warn("zabbix exception registering host", exception);
        }

        @Override
        public String toString() {
            return super.toString() + "[" + getDescription() + "]";
        }

        @Override
        public String getDescription() {
            return "Zabbix rest poll";
        }
    };

    // Schedule registration attempt once per second
    getPoller().scheduleAtFixedRate(registerJob, registrationHandler, 1000l); // TODO make configurable

    // Create a polling job for each Zabbix metric
    for (final ZabbixPollConfig<?> config : polls) {
        Callable<HttpToolResponse> pollJob = new Callable<HttpToolResponse>() {
            @Override
            public HttpToolResponse call() throws Exception {
                if (registered.get()) {
                    if (log.isTraceEnabled())
                        log.trace("zabbix polling {} for {}", entity, config);
                    byte[] body = JSON_ITEM_GET
                            .replace("{{token}}",
                                    entity.getConfig(ZabbixMonitored.ZABBIX_SERVER)
                                            .getAttribute(ZabbixServer.ZABBIX_TOKEN))
                            .replace("{{hostId}}", entity.getAttribute(ZabbixMonitored.ZABBIX_AGENT_HOSTID))
                            .replace("{{itemKey}}", config.getItemKey())
                            .replace("{{id}}", Integer.toString(id.incrementAndGet())).getBytes();

                    return HttpTool.httpPost(httpClient, baseUriProvider.get(),
                            ImmutableMap.of("Content-Type", "application/json"), body);
                } else {
                    throw new IllegalStateException("zabbix agent not yet registered");
                }
            }
        };

        // Schedule the Zabbix polling job
        AttributePollHandler<? super HttpToolResponse> pollHandler = new AttributePollHandler<HttpToolResponse>(
                config, entity, this);
        long minPeriod = Integer.MAX_VALUE; // TODO make configurable
        if (config.getPeriod() > 0)
            minPeriod = Math.min(minPeriod, config.getPeriod());
        getPoller().scheduleAtFixedRate(pollJob, pollHandler, minPeriod);
    }

}

From source file:ca.ualberta.cs.team1travelexpenseapp.gsonUtils.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }/*from w ww .  ja  v a2  s.co m*/

    final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<String, TypeAdapter<?>>();
    final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<Class<?>, TypeAdapter<?>>();
    for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
        TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
        labelToDelegate.put(entry.getKey(), delegate);
        subtypeToDelegate.put(entry.getValue(), delegate);
    }

    return new TypeAdapter<R>() {
        @Override
        public R read(JsonReader in) throws IOException {
            JsonElement jsonElement = Streams.parse(in);
            JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName);
            if (labelJsonElement == null) {
                throw new JsonParseException("cannot deserialize " + baseType
                        + " because it does not define a field named " + typeFieldName);
            }
            String label = labelJsonElement.getAsString();
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label);
            if (delegate == null) {
                throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label
                        + "; did you forget to register a subtype?");
            }
            return delegate.fromJsonTree(jsonElement);
        }

        @Override
        public void write(JsonWriter out, R value) throws IOException {
            Class<?> srcType = value.getClass();
            String label = subtypeToLabel.get(srcType);
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType);
            if (delegate == null) {
                throw new JsonParseException(
                        "cannot serialize " + srcType.getName() + "; did you forget to register a subtype?");
            }
            JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject();
            if (jsonObject.has(typeFieldName)) {
                throw new JsonParseException("cannot serialize " + srcType.getName()
                        + " because it already defines a field named " + typeFieldName);
            }
            JsonObject clone = new JsonObject();
            clone.add(typeFieldName, new JsonPrimitive(label));
            for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
                clone.add(e.getKey(), e.getValue());
            }
            Streams.write(clone, out);
        }
    };
}

From source file:ccm.pay2spawn.configurator.Configurator.java

License:Open Source License

private void setupModels() {
    mainTable.setModel(new AbstractTableModel() {
        @Override/* w  ww .j  a  v  a  2 s. c o m*/
        public int getRowCount() {
            return rootArray.size();
        }

        @Override
        public int getColumnCount() {
            return COLUMN_NAMES.length;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            JsonObject jsonObject = rootArray.get(rowIndex).getAsJsonObject();
            if (!jsonObject.has(COLUMN_KEYS[columnIndex]))
                return "";
            switch (columnIndex) {
            default:
                return jsonObject.get(COLUMN_KEYS[columnIndex]).getAsString();
            case 4:
                HashSet<String> types = new HashSet<>();
                for (JsonElement element : jsonObject.getAsJsonArray(COLUMN_KEYS[columnIndex]))
                    types.add(element.getAsJsonObject().get("type").getAsString());
                return JOINER_COMMA_SPACE.join(types);
            }
        }

        @Override
        public String getColumnName(int column) {
            return COLUMN_NAMES[column];
        }
    });

    typeList.setModel(new AbstractListModel<String>() {
        final ArrayList<String> names = TypeRegistry.getNames();

        @Override
        public int getSize() {
            return names.size();
        }

        @Override
        public String getElementAt(int index) {
            return names.get(index);
        }
    });

    rewards.setModel(new AbstractListModel<String>() {
        @Override
        public int getSize() {
            return rewardData == null ? 0 : rewardData.size();
        }

        @Override
        public String getElementAt(int index) {
            if (rewardData.get(index).getAsJsonObject().has("type"))
                return rewardData.get(index).getAsJsonObject().getAsJsonPrimitive("type").getAsString();
            else
                return "ERROR IN CONFIG - No type for reward " + index;
        }
    });
}

From source file:ccm.pay2spawn.permissions.Group.java

License:Open Source License

public Group(JsonObject jsonObject) {
    name = jsonObject.get("name").getAsString();
    if (jsonObject.has("parent"))
        parent = jsonObject.get("parent").getAsString();
    for (JsonElement node : jsonObject.getAsJsonArray("nodes"))
        nodes.add(new Node(node.getAsString()));
}

From source file:ccm.pay2spawn.permissions.Player.java

License:Open Source License

public Player(JsonObject jsonObject) {
    name = jsonObject.get("name").getAsString();
    if (jsonObject.has("groups"))
        for (JsonElement groupName : jsonObject.getAsJsonArray("groups"))
            groups.add(groupName.getAsString());
    if (jsonObject.has("overrideNodes"))
        for (JsonElement node : jsonObject.getAsJsonArray("overrideNodes"))
            overrideNodes.add(new Node(node.getAsString()));
}

From source file:ccm.pay2spawn.types.CustomEntityType.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("id").getAsString().replace("STRING:", ""));
        while (jsonObject.has(RIDING_KEY)) {
            jsonObject = jsonObject.getAsJsonObject(RIDING_KEY);
            sb.append(" riding a ").append(jsonObject.get("id").getAsString().replace("STRING:", ""));
        }/*ww w.j  ava2  s  .  c o m*/
        return sb.toString();
    }
    return id;
}