Example usage for org.json.simple JSONArray add

List of usage examples for org.json.simple JSONArray add

Introduction

In this page you can find the example usage for org.json.simple JSONArray add.

Prototype

public boolean add(E e) 

Source Link

Document

Appends the specified element to the end of this list.

Usage

From source file:net.duckling.ddl.web.controller.LynxTeamInfoController.java

@RequestMapping(params = "func=getUserByTeamCode")
public void getUserByTeamCode(HttpServletRequest req, HttpServletResponse resp) {
    VWBContainer container = VWBContainerImpl.findContainer();
    if (!validateRequest(req, container)) {
        resp.setStatus(401);/*w  ww  . j  a  v  a 2 s .c  o m*/
        return;
    }
    String teamCode = req.getParameter("teamCode");
    if (StringUtils.isEmpty(teamCode)) {
        resp.setStatus(400);
        return;
    }
    Site site = container.getSiteByName(teamCode);
    List<SimpleUser> users = teamMemberService.getTeamMembersOrderByName(site.getId());
    JSONArray userArray = new JSONArray();
    for (SimpleUser user : users) {
        userArray.add(user.getUid());
    }
    JSONObject result = new JSONObject();
    result.put("userInfo", userArray);
    Team team = teamService.getTeamByID(site.getId());
    JSONObject obj = new JSONObject();
    obj.put("teamCode", team.getName());
    obj.put("teamName", team.getDisplayName());
    List<TeamAcl> teamAcls = authorityService.getTeamAdminByTid(team.getId());
    JSONArray adminArrays = new JSONArray();
    for (TeamAcl teamAcl : teamAcls) {
        adminArrays.add(teamAcl.getUid());
    }
    obj.put("admin", adminArrays);
    obj.put("accessType", team.getAccessType());
    result.put("teamInfo", obj);
    JsonUtil.writeJSONObject(resp, result);
}

From source file:gwap.game.quiz.QuizSessionBean.java

public JSONObject getJSONResult() {

    boolean imageFound = createWoelfflinResource();
    if (!imageFound) {
        // retry/*from   w w w .ja  va2  s. c om*/
        imageFound = createWoelfflinResource();
        if (!imageFound) {
            log.error("Could not find 15 valid images for quiz game setup");
        }
    }

    JSONArray gameArray = new JSONArray();

    for (int i = 0; i < 15; ++i) {
        gameArray.add(questions.get(i).generateJSONObject());
    }

    this.jsonResult = new JSONObject();
    jsonResult.put("Array", gameArray);
    return this.jsonResult;
}

From source file:com.conwet.silbops.msg.UnadvertiseMsg.java

@Override
@SuppressWarnings("unchecked")
public JSONObject getPayloadAsJSON() {

    JSONObject json = new JSONObject();
    json.put("advertise", advertise.toJSON());
    json.put("context", context.toJSON());

    JSONArray uncov = new JSONArray();
    for (Advertise fil : uncovered) {

        uncov.add(fil.toJSON());
    }/*from w w  w.  j ava2s.  c om*/
    json.put("uncovered", uncov);

    return json;
}

From source file:edu.anu.spice.SemanticTuple.java

@SuppressWarnings("unchecked")
@Override// ww w.j ava  2  s .  c  o m
public String toJSONString() {
    JSONObject jsonObj = new JSONObject();
    JSONArray tuple = new JSONArray();
    for (SemanticConcept concept : this.tuple) {
        tuple.add(concept.toJSONString());
    }
    jsonObj.put("tuple", tuple);
    jsonObj.put("truth_value", this.truthValue);
    return JSONValue.toJSONString(jsonObj);
}

From source file:de.themoep.chestshoptools.ShopInfoCommand.java

public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
    if (args.length > 0) {
        return false;
    }/*from w  ww .  j  a  va2 s .c o m*/
    if (!(sender instanceof Player)) {
        sender.sendMessage(ChatColor.RED + "This command can only be run by a player!");
        return true;
    }
    Block lookingAt = ((Player) sender).getTargetBlock((Set<Material>) null, 10);
    if (lookingAt == null) {
        sender.sendMessage(
                ChatColor.RED + "Please look at a shop sign or chest!" + ChatColor.DARK_GRAY + " (0)");
        return true;
    }
    Sign shopSign = null;
    if (lookingAt.getState() instanceof Chest) {
        shopSign = uBlock.getConnectedSign((Chest) lookingAt.getState());
    } else if (lookingAt.getState() instanceof Sign && ChestShopSign.isValid(lookingAt)) {
        shopSign = (Sign) lookingAt.getState();
    }
    if (shopSign == null) {
        sender.sendMessage(
                ChatColor.RED + "Please look at a shop sign or chest!" + ChatColor.DARK_GRAY + " (1)");
        return true;
    }

    String name = shopSign.getLine(ChestShopSign.NAME_LINE);
    String quantity = shopSign.getLine(ChestShopSign.QUANTITY_LINE);
    String prices = shopSign.getLine(ChestShopSign.PRICE_LINE);
    String material = shopSign.getLine(ChestShopSign.ITEM_LINE);

    String ownerName = NameManager.getFullNameFor(NameManager.getUUIDFor(name));
    ItemStack item = MaterialUtil.getItem(material);

    if (item == null || !NumberUtil.isInteger(quantity)) {
        sender.sendMessage(Messages.prefix(Messages.INVALID_SHOP_DETECTED));
        return true;
    }

    sender.sendMessage(Messages.prefix(ChatColor.GREEN + "Besitzer: " + ChatColor.WHITE + ownerName));
    if (plugin.getShowItem() == null) {
        sender.sendMessage(Messages.prefix(ChatColor.GREEN + "Item: " + ChatColor.WHITE + material));
    } else {
        String itemJson = plugin.getShowItem().getItemConverter().itemToJson(item, Level.FINE);

        String icon = "";
        if (plugin.getShowItem().useIconRp()) {
            icon = plugin.getShowItem().getIconRpMap().getIcon(item, true);
        }

        JSONArray textJson = new JSONArray();

        textJson.add(new JSONObject(ImmutableMap.of("text", Messages.prefix(ChatColor.GREEN + "Item: "))));

        JSONObject hoverJson = new JSONObject();
        hoverJson.put("action", "show_item");
        hoverJson.put("value", itemJson);
        ChatColor nameColor = plugin.getShowItem().getItemConverter().getNameColor(item);

        if (plugin.getShowItem().useIconRp()) {
            JSONObject iconJson = new JSONObject();
            iconJson.put("text", icon);
            iconJson.put("hoverEvent", hoverJson);

            textJson.add(iconJson);
        }

        JSONObject typeJson = new JSONObject();
        typeJson.put("translate", plugin.getShowItem().getItemConverter().getTranslationKey(item));
        JSONArray translateWith = new JSONArray();
        translateWith.addAll(plugin.getShowItem().getItemConverter().getTranslateWith(item));
        if (!translateWith.isEmpty()) {
            typeJson.put("with", translateWith);
        }

        typeJson.put("hoverEvent", hoverJson);
        typeJson.put("color", nameColor.name().toLowerCase());

        textJson.add(typeJson);

        String itemName = plugin.getShowItem().getItemConverter().getCustomName(item);
        if (!itemName.isEmpty()) {
            textJson.add(new JSONObject(ImmutableMap.of("text", ": ", "color", "green")));

            JSONObject nameJson = new JSONObject();
            nameJson.put("text", itemName);
            nameJson.put("hoverEvent", hoverJson);
            nameJson.put("color", nameColor.name().toLowerCase());

            textJson.add(nameJson);
        }

        plugin.getShowItem().tellRaw((Player) sender, textJson.toString());
    }
    sender.sendMessage(Messages.prefix(ChatColor.GREEN + "Anzahl: " + ChatColor.WHITE + quantity));
    sender.sendMessage(Messages.prefix(ChatColor.GREEN + "Preis: " + ChatColor.WHITE + prices));

    return true;
}

From source file:gr.iit.demokritos.cru.cps.api.SubmitUserFormalEvaluationList.java

public JSONObject processRequest() throws IOException, Exception {

    String response_code = "e0";
    long user_id = 0;

    String[] users = users_list.split(";");
    ArrayList<Long> users_id = new ArrayList<Long>();

    for (int i = 0; i < users.length; i++) {
        users_id.add(Long.parseLong(users[i]));
    }//  w  w  w  .  j  a v  a 2  s . c  o  m

    String location = (String) properties.get("location");
    String database_name = (String) properties.get("database_name");
    String username = (String) properties.get("username");
    String password = (String) properties.get("password");

    MySQLConnector mysql = new MySQLConnector(location, database_name, username, password);

    try {

        Connection connection = mysql.connectToCPSDatabase();
        Statement stmt = connection.createStatement();

        ResultSet rs = stmt.executeQuery("SELECT window FROM windows WHERE current_window=1");
        int window = -1;
        while (rs.next()) {
            window = rs.getInt(1);
        }
        rs.close();

        UserManager um = new UserManager(Long.parseLong(application_key), users_id);
        CreativityExhibitModelController cemc = new CreativityExhibitModelController(window,
                Long.parseLong(application_key), user_id, users_id);

        boolean isvalid = false;
        isvalid = um.validateClientApplication(mysql);
        if (isvalid == true) {
            Iterator it = users_id.iterator();

            while (it.hasNext()) {
                um.setUser_id((Long) it.next());
                isvalid = um.validateUser(mysql);
                if (isvalid == false) {
                    break;
                }
            }
            if (isvalid == true) {
                cemc.storeFormalEvaluation(mysql);
                response_code = "OK";
            } else {
                response_code = "e102";
            }
        } else {
            response_code = "e101";
        }
    } catch (NumberFormatException ex) {
        response_code = "e101";
        Logger.getLogger(CreateUser.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(CreateUser.class.getName()).log(Level.SEVERE, null, ex);
    }

    JSONArray list = new JSONArray();

    for (Long temp_user : users_id) {
        list.add(Long.toString(temp_user));
    }

    JSONObject obj = new JSONObject();

    obj.put("application_key", application_key);
    obj.put("user_id", Long.toString(user_id));
    obj.put("users_id", list);
    obj.put("response_code", response_code);

    return obj;
}

From source file:com.facebook.tsdb.tsdash.server.PlotEndpoint.java

@Override
@SuppressWarnings("unchecked")
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();
    try {//from ww  w.ja v  a 2 s  .com
        // decode parameters
        String jsonParams = request.getParameter("params");
        if (jsonParams == null) {
            throw new Exception("Parameters not specified");
        }
        JSONObject jsonParamsObj = (JSONObject) JSONValue.parse(jsonParams);
        long tsFrom = (Long) jsonParamsObj.get("tsFrom");
        long tsTo = (Long) jsonParamsObj.get("tsTo");
        long width = (Long) jsonParamsObj.get("width");
        long height = (Long) jsonParamsObj.get("height");
        boolean surface = (Boolean) jsonParamsObj.get("surface");
        boolean palette = false;
        if (jsonParams.contains("palette")) {
            palette = (Boolean) jsonParamsObj.get("palette");
        }
        JSONArray metricsArray = (JSONArray) jsonParamsObj.get("metrics");
        if (metricsArray.size() == 0) {
            throw new Exception("No metrics to fetch");
        }
        MetricQuery[] metricQueries = new MetricQuery[metricsArray.size()];
        for (int i = 0; i < metricsArray.size(); i++) {
            metricQueries[i] = MetricQuery.fromJSONObject((JSONObject) metricsArray.get(i));
        }
        TsdbDataProvider dataProvider = TsdbDataProviderFactory.get();
        long ts = System.currentTimeMillis();
        Metric[] metrics = new Metric[metricQueries.length];
        for (int i = 0; i < metrics.length; i++) {
            MetricQuery q = metricQueries[i];
            metrics[i] = dataProvider.fetchMetric(q.name, tsFrom, tsTo, q.tags, q.orders);
            metrics[i] = metrics[i].dissolveTags(q.getDissolveList(), q.aggregator);
            if (q.rate) {
                metrics[i].computeRate();
            }
        }
        long loadTime = System.currentTimeMillis() - ts;
        // check to see if we have data
        boolean hasData = false;
        for (Metric metric : metrics) {
            if (metric.hasData()) {
                hasData = true;
                break;
            }
        }
        if (!hasData) {
            throw new Exception("No data");
        }
        JSONObject responseObj = new JSONObject();
        JSONArray encodedMetrics = new JSONArray();
        for (Metric metric : metrics) {
            encodedMetrics.add(metric.toJSONObject());
        }
        // plot just the first metric for now
        GnuplotProcess gnuplot = GnuplotProcess.create(surface);
        GnuplotOptions options = new GnuplotOptions(surface);
        options.enablePalette(palette);
        options.setDimensions((int) width, (int) height).setTimeRange(tsFrom, tsTo);
        String plotFilename = gnuplot.plot(metrics, options);
        gnuplot.close();

        responseObj.put("metrics", encodedMetrics);
        responseObj.put("loadtime", loadTime);
        responseObj.put("ploturl", generatePlotURL(plotFilename));
        out.println(responseObj.toJSONString());
        long renderTime = System.currentTimeMillis() - ts - loadTime;
        logger.info("[Plot] time frame: " + (tsTo - tsFrom) + "s, " + "load time: " + loadTime + "ms, "
                + "render time: " + renderTime + "ms");
    } catch (Throwable e) {
        out.println(getErrorResponse(e));
    }
    out.close();
}

From source file:com.hurence.logisland.repository.json.JsonTagsFileParser.java

/**
 * parses the file and returns a dictionnary of domain / tags
 *
 * @param filename// w ww.j a v  a  2 s  .c  o m
 * @return
 */
public Map<String, List<String>> parse(String filename) {

    Map<String, List<String>> repository = new HashMap<>();
    JSONParser parser = new JSONParser();
    int domainCount = 0;

    try {

        logger.debug("parsing json file : " + filename);
        Object obj = parser.parse(new FileReader(filename));

        JSONArray domains = (JSONArray) obj;

        for (Object object : domains) {
            domainCount++;
            JSONObject jsonObject = (JSONObject) object;
            String domain = (String) jsonObject.get("term");

            JSONArray tags = (JSONArray) jsonObject.get("tags");

            String company = (String) jsonObject.get("company");
            if (company != null) {
                tags.add(company);
            }

            repository.put(domain, tags);
        }

        logger.debug("succesfully parsed " + domainCount + "domains");

    } catch (ParseException | IOException ex) {
        logger.error(ex.getMessage());
    }

    return repository;

}

From source file:com.rackspacecloud.blueflood.outputs.serializers.JSONHistogramOutputSerializer.java

private JSONArray transformDataToJSONArray(MetricData metricData) throws SerializationException {
    Points points = metricData.getData();
    final JSONArray data = new JSONArray();
    final Set<Map.Entry<Long, Points.Point>> dataPoints = points.getPoints().entrySet();
    for (Map.Entry<Long, Points.Point> point : dataPoints) {
        data.add(toJSON(point.getKey(), point.getValue(), metricData.getUnit()));
    }//from w  ww  .  j  a v a  2  s.c o  m

    return data;
}

From source file:com.dbay.apns4j.model.Payload.java

@SuppressWarnings("unchecked")
@Override//from w  w w  .  j  a  v  a 2 s .  com
public String toString() {
    JSONObject object = new JSONObject();
    JSONObject apsObj = new JSONObject();
    if (getAlert() != null) {
        apsObj.put("alert", getAlert());
    } else {
        if (getAlertBody() != null || getAlertLocKey() != null) {
            JSONObject alertObj = new JSONObject();
            putIntoJson("body", getAlertBody(), alertObj);
            putIntoJson("action-loc-key", getAlertActionLocKey(), alertObj);
            putIntoJson("loc-key", getAlertLocKey(), alertObj);
            putIntoJson("launch-image", getAlertLaunchImage(), alertObj);
            if (getAlertLocArgs() != null) {
                JSONArray array = new JSONArray();
                for (String str : getAlertLocArgs()) {
                    array.add(str);
                }
                alertObj.put("loc-args", array);
            }
            apsObj.put("alert", alertObj);
        }
    }

    if (getBadge() != null) {
        apsObj.put("badge", getBadge().intValue());
    }
    putIntoJson("sound", getSound(), apsObj);

    if (getContentAvailable() != null) {
        apsObj.put("content-available", getContentAvailable().intValue());
    }

    object.put(APS, apsObj);
    if (getParams() != null) {
        for (Entry<String, Object> e : getParams().entrySet()) {
            object.put(e.getKey(), e.getValue());
        }
    }
    return object.toString();
}