Example usage for com.google.gson JsonObject getAsJsonArray

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

Introduction

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

Prototype

public JsonArray getAsJsonArray(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonArray.

Usage

From source file:me.jewsofhazard.pcmrbot.twitch.TwitchUtilities.java

License:Open Source License

/**
 * Checks if the sender is subscribed to channel
 * /*from  ww w  .ja v a 2s.  com*/
 * @param sender
 * @param channel
 * @return - true if sender is subscribed to channel
 */
public static boolean isSubscriber(String sender, String channel) {
    try {
        String userOAuth = Database.getUserOAuth(channel.substring(1));
        String nextUrl = "https://api.twitch.tv/kraken/channels/" + channel.substring(0)
                + "/subscriptions/?oauth_token=" + userOAuth;
        JsonObject obj = new JsonParser()
                .parse(new JsonReader(new InputStreamReader(new URL(nextUrl).openStream()))).getAsJsonObject();
        if (obj.get("error") != null) { // ie it finds it
            return false;
        } else { // it does not find it
            int count = subscriberCount(channel, userOAuth);
            int pages = count / 25;
            if (count % 25 != 0) {
                pages++;
            }
            for (int i = 0; i < pages; i++) {
                for (int j = 0; j < 25; j++) {
                    if (sender.equalsIgnoreCase(obj.getAsJsonArray("subscriptions").get(j).getAsJsonObject()
                            .getAsJsonPrimitive("display_name").getAsString())) {
                        return true;
                    }
                }
                nextUrl = URLEncoder
                        .encode(obj.getAsJsonArray("_links").get(1).getAsJsonPrimitive().getAsString()
                                + "?oauth_token=" + userOAuth, CHARSET);
                obj = new JsonParser()
                        .parse(new JsonReader(new InputStreamReader(new URL(nextUrl).openStream())))
                        .getAsJsonObject();
            }
            return false;
        }
    } catch (JsonIOException | JsonSyntaxException | IOException e) {
        logger.log(Level.SEVERE,
                "An error occurred checking if " + sender + " is following " + channel.substring(1), e);
    }
    return false;
}

From source file:me.lachlanap.summis.update.UpdateInformationGrabber.java

License:Open Source License

private void process(String allText) {
    JsonObject json = new JsonParser().parse(allText).getAsJsonObject();
    if (json.get("version").getAsInt() != FORMAT_VERSION)
        throw new RuntimeException("Format version " + json.get("version").getAsInt() + " is not supported.");

    versions.clear();/*from   w  ww.  j a v a  2 s.c  o m*/
    for (JsonElement element : json.getAsJsonArray("versions")) {
        versions.add(parseVersion(element.getAsJsonObject()));
    }

    // Sort latest to earliest
    Collections.sort(versions, new Comparator<VersionInfo>() {
        @Override
        public int compare(VersionInfo o1, VersionInfo o2) {
            return -o1.version.compareTo(o2.version);
        }
    });
}

From source file:me.lachlanap.summis.update.UpdateInformationGrabber.java

License:Open Source License

private VersionInfo parseVersion(JsonObject versionJson) {
    Version version = Version.parse(versionJson.get("number").getAsString());
    String description = versionJson.get("description").getAsString();
    FileSet diffSet = parseFileSet(versionJson.getAsJsonArray("diff"));
    FileSet fullSet = parseFileSet(versionJson.getAsJsonArray("full"));

    return new VersionInfo(version, description, diffSet, fullSet);
}

From source file:me.lucko.luckperms.common.commands.impl.misc.ApplyEditsCommand.java

License:MIT License

@Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, List<String> args, String label)
        throws CommandException {
    String code = args.get(0);/*from www.  ja va 2 s. c  o m*/
    String who = args.size() == 2 ? args.get(1) : null;

    if (code.isEmpty()) {
        Message.APPLY_EDITS_INVALID_CODE.send(sender, code);
        return CommandResult.INVALID_ARGS;
    }

    JsonObject data = WebEditorUtils.getDataFromGist(code);
    if (data == null) {
        Message.APPLY_EDITS_UNABLE_TO_READ.send(sender, code);
        return CommandResult.FAILURE;
    }

    if (who == null) {
        if (!data.has("who") || data.get("who").getAsString().isEmpty()) {
            Message.APPLY_EDITS_NO_TARGET.send(sender);
            return CommandResult.STATE_ERROR;
        }

        who = data.get("who").getAsString();
    }

    PermissionHolder holder = WebEditorUtils.getHolderFromIdentifier(plugin, sender, who);
    if (holder == null) {
        // the #getHolderFromIdentifier method will send the error message onto the sender
        return CommandResult.STATE_ERROR;
    }

    if (ArgumentPermissions.checkModifyPerms(plugin, sender, getPermission().get(), holder)) {
        Message.COMMAND_NO_PERMISSION.send(sender);
        return CommandResult.NO_PERMISSION;
    }

    ExtendedLogEntry.build().actor(sender).acted(holder).action("applyedits", code).build().submit(plugin,
            sender);

    Set<NodeModel> rawNodes = WebEditorUtils.deserializePermissions(data.getAsJsonArray("nodes"));

    Set<Node> before = new HashSet<>(holder.getEnduringNodes().values());
    Set<Node> nodes = rawNodes.stream().map(NodeModel::toNode).collect(Collectors.toSet());
    holder.setEnduringNodes(nodes);

    Map.Entry<Set<Node>, Set<Node>> diff = diff(before, nodes);
    int additions = diff.getKey().size();
    int deletions = diff.getValue().size();
    String additionsSummary = "addition" + (additions == 1 ? "" : "s");
    String deletionsSummary = "deletion" + (deletions == 1 ? "" : "s");

    Message.APPLY_EDITS_SUCCESS.send(sender, holder.getFriendlyName());
    Message.APPLY_EDITS_SUCCESS_SUMMARY.send(sender, additions, additionsSummary, deletions, deletionsSummary);
    for (Node n : diff.getKey()) {
        Message.APPLY_EDITS_DIFF_ADDED.send(sender, formatNode(n));
    }
    for (Node n : diff.getValue()) {
        Message.APPLY_EDITS_DIFF_REMOVED.send(sender, formatNode(n));
    }

    SharedSubCommand.save(holder, sender, plugin);
    return CommandResult.SUCCESS;
}

From source file:me.lucko.luckperms.common.commands.misc.ApplyEditsCommand.java

License:MIT License

private boolean read(JsonObject data, Sender sender, LuckPermsPlugin plugin) {
    if (!data.has("who") || data.get("who").getAsString().isEmpty()) {
        Message.APPLY_EDITS_NO_TARGET.send(sender);
        return false;
    }/*from w ww . j  a va  2  s .  c o  m*/

    String who = data.get("who").getAsString();
    PermissionHolder holder = WebEditor.getHolderFromIdentifier(plugin, sender, who);
    if (holder == null) {
        // the #getHolderFromIdentifier method will send the error message onto the sender
        return false;
    }

    if (ArgumentPermissions.checkModifyPerms(plugin, sender, getPermission().get(), holder)) {
        Message.COMMAND_NO_PERMISSION.send(sender);
        return false;
    }

    Set<NodeDataContainer> nodes = WebEditor.deserializePermissions(data.getAsJsonArray("nodes"));

    Set<Node> before = new HashSet<>(holder.enduringData().immutable().values());
    Set<Node> after = nodes.stream().map(NodeDataContainer::toNode).collect(Collectors.toSet());

    Map.Entry<Set<Node>, Set<Node>> diff = diff(before, after);
    Set<Node> diffAdded = diff.getKey();
    Set<Node> diffRemoved = diff.getValue();

    int additions = diffAdded.size();
    int deletions = diffRemoved.size();

    if (additions == 0 && deletions == 0) {
        return false;
    }

    holder.setNodes(NodeMapType.ENDURING, after);

    for (Node n : diffAdded) {
        ExtendedLogEntry.build().actor(sender).acted(holder)
                .action("webeditor", "add", n.getPermission(), n.getValue(), n.getFullContexts()).build()
                .submit(plugin, sender);
    }
    for (Node n : diffRemoved) {
        ExtendedLogEntry.build().actor(sender).acted(holder)
                .action("webeditor", "remove", n.getPermission(), n.getValue(), n.getFullContexts()).build()
                .submit(plugin, sender);
    }

    String additionsSummary = "addition" + (additions == 1 ? "" : "s");
    String deletionsSummary = "deletion" + (deletions == 1 ? "" : "s");

    Message.APPLY_EDITS_SUCCESS.send(sender, holder.getFriendlyName());
    Message.APPLY_EDITS_SUCCESS_SUMMARY.send(sender, additions, additionsSummary, deletions, deletionsSummary);
    for (Node n : diffAdded) {
        Message.APPLY_EDITS_DIFF_ADDED.send(sender, formatNode(plugin.getLocaleManager(), n));
    }
    for (Node n : diffRemoved) {
        Message.APPLY_EDITS_DIFF_REMOVED.send(sender, formatNode(plugin.getLocaleManager(), n));
    }
    StorageAssistant.save(holder, sender, plugin);
    return true;
}

From source file:modelo.PreCirculacionDeserializer.java

@Override
public PreCirculacion deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    PreCirculacion pc = new PreCirculacion();
    JsonObject jo = json.getAsJsonObject();
    pc.setColor(jo.get("color").getAsString());
    pc.setEstacionLlegada(jo.get("estacionLlegada").getAsInt());
    pc.setEstacionSalida(jo.get("estacionSalida").getAsInt());
    pc.setHoraInicial(jo.get("horaInicio").getAsDouble());
    pc.setMarchaTipo(jo.get("marchaTipo").getAsInt());
    pc.setPrefijoNumeracion(jo.get("prefijoNumeracion").getAsInt());
    //        System.out.println(json.getAsJsonObject().toString());
    JsonArray ja = jo.getAsJsonArray("teps");
    //        System.out.println("Deserializando TEPS: "+ja);
    ArrayList<EstacionTramoParada> estacionTramoParadaList = new ArrayList<>();
    for (int i = 0; i < ja.size(); i++) {
        EstacionTramoParadaPK tepPK = new EstacionTramoParadaPK();
        tepPK.setIdEstacion(ja.get(i).getAsJsonObject().get("estacion").getAsDouble());
        EstacionTramoParada tep = new EstacionTramoParada();
        tep.setEstacionTramoParadaPK(tepPK);
        //            EstacionTramoParada tep= new EstacionTramoParada(pc.getPreCirculacionPK().getIdProgramacionHoraria(), pc.getPreCirculacionPK().getIdPreCirculacion(), ja.get(i).getAsJsonObject().get("estacion").getAsDouble());

        tep.setTiempo(ja.get(i).getAsJsonObject().get("tramo").getAsInt());
        //            tep.setParada(ja.get(i).getAsJsonObject().get("parada").getAsInt());
        try {/*from www  .ja va 2s  .c  o m*/
            if (ja.get(i).getAsJsonObject().get("parada").isJsonNull() == true) {
                tep.setParada(0);
            } else {
                tep.setParada(ja.get(i).getAsJsonObject().get("parada").getAsInt());
            }
        } catch (NullPointerException e) {
            tep.setParada(0);
        }
        estacionTramoParadaList.add(tep);
    }
    pc.setEstacionTramoParadaList(estacionTramoParadaList);
    return pc;
}

From source file:monasca.common.middleware.FilterUtils.java

License:Apache License

private static void wrapRequestFromHttpV3Response(ServletRequest req, String data) {
    StringBuilder tenants = new StringBuilder();
    StringBuilder nonTenants = new StringBuilder();
    JsonParser jp = new JsonParser();
    JsonObject token = jp.parse(data).getAsJsonObject().get("token").getAsJsonObject();
    // Domain Scoped Token
    if (token.get("domain") != null) {
        JsonObject domain = token.get("domain").getAsJsonObject();
        req.setAttribute(AUTH_DOMAIN_ID, domain.get("id").getAsString());
        if (domain.get("name") != null) {
            req.setAttribute(AUTH_DOMAIN_NAME, domain.get("name").getAsString());
        }/*www .jav a  2  s.  com*/
    }
    // Project Scoped Token
    if (token.get("project") != null) {
        JsonObject project = token.get("project").getAsJsonObject();
        req.setAttribute(AUTH_PROJECT_ID, project.get("id").getAsString());
        req.setAttribute(AUTH_PROJECT_NAME, project.get("name").getAsString());

        JsonObject projectDomain = project.get("domain").getAsJsonObject();
        // special case where the value of id is null and the
        // projectDomain.get("id") != null
        if (!projectDomain.get("id").equals(JsonNull.INSTANCE)) {
            req.setAttribute(AUTH_PROJECT_DOMAIN_ID, projectDomain.get("id").getAsString());
        }
        if (projectDomain.get("name") != null) {
            req.setAttribute(AUTH_PROJECT_DOMAIN_NAME, projectDomain.get("name"));
        }
    }
    // User info
    if (token.get("user") != null) {
        JsonObject user = token.get("user").getAsJsonObject();
        req.setAttribute(AUTH_USER_ID, user.get("id").getAsString());
        req.setAttribute(AUTH_USER_NAME, user.get("name").getAsString());

        JsonObject userDomain = user.get("domain").getAsJsonObject();
        if (userDomain.get("id") != null) {
            req.setAttribute(AUTH_USER_DOMAIN_ID, userDomain.get("id").getAsString());
        }
        if (userDomain.get("name") != null) {
            req.setAttribute(AUTH_USER_DOMAIN_NAME, userDomain.get("name").getAsString());
        }

    }
    // Roles
    JsonArray roles = token.getAsJsonArray("roles");
    if (roles != null) {
        Iterator<JsonElement> it = roles.iterator();
        StringBuilder roleBuilder = new StringBuilder();
        while (it.hasNext()) {

            //Changed to meet my purposes
            JsonObject role = it.next().getAsJsonObject();
            String currentRole = role.get("name").getAsString();
            roleBuilder.append(currentRole).append(",");
        }
        //My changes to meet my needs
        req.setAttribute(AUTH_ROLES, roleBuilder.toString());
    }
    String tenantRoles = (tenants.length() > 0) ? tenants.substring(1) : tenants.toString();
    String nonTenantRoles = (nonTenants.length() > 0) ? nonTenants.substring(1) : nonTenants.toString();
    if (!tenantRoles.equals("")) {
        req.setAttribute(AUTH_ROLES, tenantRoles);
    }
    if (!nonTenantRoles.equals("")) {
        req.setAttribute(AUTH_HP_IDM_ROLES, nonTenantRoles);
    }
    // Catalog
    if (token.get("catalog") != null && appConfig.isIncludeCatalog()) {
        JsonArray catalog = token.get("catalog").getAsJsonArray();
        req.setAttribute(AUTH_SERVICE_CATALOG, catalog.toString());
    }
}

From source file:net.atos.ari.vital.tassproxy.TaaSCMClient.java

License:Apache License

public ArrayList<String> getThingServices() {
    logger.debug("Calling Get Thing Services to the CM for getting the full list");
    ArrayList<String> myList = null;
    try {/*from  w  w w  . ja  v a2  s .c  o  m*/
        // Retrieve the JasonArray object with the list
        String resList = null; /*EGO myClient.getContextThingServices();*/
        JsonElement jelement = new JsonParser().parse(resList);
        JsonObject parsedRes = jelement.getAsJsonObject();
        JsonArray listArray = parsedRes.getAsJsonArray("list");

        // Transform the JasonArray in an ArrayList
        myList = new ArrayList<String>();
        for (int i = 0; i < listArray.size(); i++) {
            myList.add(listArray.get(i).getAsString());
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        return new ArrayList<String>();
    }

    logger.debug("Invocation done! Retrieved: " + myList.size());
    return myList;
}

From source file:net.atos.ari.vital.tassproxy.TaaSCMClient.java

License:Apache License

public ArrayList<String> getEquivalentThingServices(String feature, ThingLocation location,
        String thingServiceId) {//ww w . j  a  va  2 s . c o  m
    logger.debug("Looking for equivalents related to " + thingServiceId);
    logger.debug("Calling Get Thing Services to the CM with feature " + feature + " in "
            + location.getLocationIdentifier());
    ArrayList<String> myList = new ArrayList<String>();
    try {
        // Retrieve the JasonArray object with the list         
        String resList = null;
        if (location.getEnvironment()) {
            resList = null;
        } else {
            resList = null; /*myClient.getContextThingServices(feature, location.getLocationIdentifier(), location.getLocationKeyword(), location.getFloor());*/
        }

        logger.debug("Data received: " + resList);

        JsonElement jelement = new JsonParser().parse(resList);
        JsonObject parsedRes = jelement.getAsJsonObject();
        JsonArray listArray = parsedRes.getAsJsonArray("list");
        JsonArray listEqArray = parsedRes.getAsJsonArray("eq_list");

        // Transform the JasonArray in an ArrayList and look for the current thing service         
        int position = -1;
        for (int i = 0; i < listArray.size(); i++) {
            if (listArray.get(i).getAsString().equalsIgnoreCase(thingServiceId)) {
                // We found our thing service, so we take the position for the equivalents list
                position = i;
                break;
            }

        }

        if (position == -1) {
            // If the thing service didn't appear, then provide empty list
            logger.error("The thing service wasn't retrieved. Unable to find equivalents!");
            return myList;
        }

        // Transform the Equivalent Services matrix in an ArrayList of ArrayList
        JsonArray currentList = listEqArray.get(position).getAsJsonArray();
        for (int j = 0; j < currentList.size(); j++) {
            String currentEquivalent = currentList.get(j).getAsString();
            if (!currentEquivalent.equalsIgnoreCase(thingServiceId)) {
                myList.add(currentEquivalent);
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }

    logger.debug("Invocation done! Equivalents found: " + myList.size());

    return myList;
}

From source file:net.bluemix.tutorial.vision.PatchedCredentialUtils.java

License:Open Source License

/**
 * Returns the apiKey from the VCAP_SERVICES or null if doesn't exists. If
 * plan is specified, then only credentials for the given plan will be
 * returned./*w  w  w .j av a2s .c o m*/
 * 
 * @param serviceName
 *          the service name
 * @param plan
 *          the service plan: standard, free or experimental
 * @return the API key
 */
public static String getAPIKey(String serviceName, String plan) {
    if (serviceName == null || serviceName.isEmpty())
        return null;

    final JsonObject services = getVCAPServices();
    if (services == null)
        return null;

    for (final Entry<String, JsonElement> entry : services.entrySet()) {
        final String key = entry.getKey();
        if (key.startsWith(serviceName)) {
            final JsonArray servInstances = services.getAsJsonArray(key);
            for (final JsonElement instance : servInstances) {
                final JsonObject service = instance.getAsJsonObject();
                final String instancePlan = service.get(PLAN).getAsString();
                if (plan == null || plan.equalsIgnoreCase(instancePlan)) {
                    final JsonObject credentials = instance.getAsJsonObject().getAsJsonObject(CREDENTIALS);
                    if (serviceName.equalsIgnoreCase(WATSON_VISUAL_RECOGNITION)) {
                        return credentials.get(APIKEY).getAsString();
                    }
                }
            }
        }
    }
    return null;
}