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:com.appzone.sim.services.handlers.ReceiveSmsCheckServiceHandler.java

@Override
protected String doProcess(HttpServletRequest request) {

    String address = request.getParameter(KEY_ADDRESS);
    String sinceStr = request.getParameter(KEY_SINCE);
    logger.debug("request sms messages for: {} since: {}", address, sinceStr);
    long since = Long.parseLong(sinceStr);

    List<Sms> messages = smsRepository.find(address, since);

    JSONArray list = new JSONArray();

    for (Sms sms : messages) {
        JSONObject json = new JSONObject();
        json.put(JSON_KEY_MESSAGE, sms.getMessage());
        json.put(JSON_KEY_RECEIVED_DATE, sms.getReceivedDate());

        list.add(json);
    }/*  ww  w.  j  a v a  2s.  c  om*/

    logger.debug("returning response: {}", list);

    return list.toJSONString();
}

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

/**
 * ?teamteam admin//from   www  .ja v  a 2s .  c  o m
 * @param req
 * @param resp
 */
@RequestMapping(params = "func=getAllTeam")
public void getAllTeam(HttpServletRequest req, HttpServletResponse resp) {
    VWBContainer container = VWBContainerImpl.findContainer();
    if (!validateRequest(req, container)) {
        resp.setStatus(401);
        return;
    }
    List<Team> teams = teamService.getAllTeams();
    JSONArray teamArray = new JSONArray();
    for (Team team : teams) {
        if (Team.PESONAL_TEAM.equals(team.getType())) {
            continue;
        }
        teamArray.add(team.getName());
    }
    JsonUtil.writeJSONObject(resp, teamArray);
}

From source file:org.kitodo.data.index.elasticsearch.type.BatchType.java

@SuppressWarnings("unchecked")
@Override//ww  w . j av  a 2s  . c  o m
public HttpEntity createDocument(Batch batch) {

    LinkedHashMap<String, String> orderedBatchMap = new LinkedHashMap<>();
    orderedBatchMap.put("title", batch.getTitle());
    String type = batch.getType() != null ? batch.getType().toString() : "null";
    orderedBatchMap.put("type", type);

    JSONArray processes = new JSONArray();
    List<Process> batchProcesses = batch.getProcesses();
    for (Process process : batchProcesses) {
        JSONObject processObject = new JSONObject();
        processObject.put("id", process.getId().toString());
        processes.add(processObject);
    }

    JSONObject batchObject = new JSONObject(orderedBatchMap);
    batchObject.put("processes", processes);

    return new NStringEntity(batchObject.toJSONString(), ContentType.APPLICATION_JSON);
}

From source file:fr.nantes.web.quizz.servlets.Adddirectors.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    int nbdirectors = Integer.parseInt(request.getParameter("nbdirectors"));

    JSONArray result = new JSONArray();
    JSONObject map = new JSONObject();
    if (nbdirectors > Requetesdatastore.getcountdirectors()) {
        if (Requetesdatastore.adddirectors(nbdirectors)) {
            map.put("count", nbdirectors);
            result.add(map);
        } else {/*w  ww .  j  a  va  2  s.c o m*/
            map.put("count", 0);
            result.add(map);
        }
    } else {
        map.put("count", -100);
        result.add(map);
    }
    response.setContentType("application/json;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {

        out.println(result);
    }
}

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

private JSONObject toJSON(long timestamp, Points.Point point, String unit) throws SerializationException {
    final JSONObject object = new JSONObject();
    object.put("timestamp", timestamp);

    if (!(point.getData() instanceof HistogramRollup)) {
        throw new SerializationException("Unsupported type. HistogramRollup expected.");
    }/*  w  ww. ja v  a 2 s.  co m*/

    HistogramRollup histogramRollup = (HistogramRollup) point.getData();

    final JSONArray hist = new JSONArray();
    for (Bin<SimpleTarget> bin : histogramRollup.getBins()) {
        final JSONObject obj = new JSONObject();
        obj.put("mean", bin.getMean());
        obj.put("count", bin.getCount());
        hist.add(obj);
    }
    object.put("histogram", hist);

    return object;
}

From source file:workspace.java

private JSONArray getJsonArrayFromStringArray(String[] a, String[] b) {
    JSONObject[] obj = new JSONObject[a.length];
    JSONArray ja = new JSONArray();
    for (int i = 0; i < a.length; i++) {
        obj[i] = new JSONObject();
        obj[i].put("pa", b[i]);
        obj[i].put("stud", a[i]);
        ja.add(obj[i]);
    }// w  ww .  j  a v  a 2s  .  co m
    return ja;
}

From source file:co.alligo.toasted.Servers.java

public JSONArray getServers() {
    String[] serveruris = servers.keySet().toArray(new String[servers.keySet().size()]);
    JSONArray jsonarray = new JSONArray();

    for (int x = 0; x < serveruris.length; x++) {
        if ((servers.get(serveruris[x]) >= expirationTime)) {
            servers.remove(serveruris[x]);
        }/*from   www .  j  a va2s .c  o m*/
    }

    for (int x = 0; x < serveruris.length; x++)
        jsonarray.add(serveruris[x]);

    return jsonarray;
}

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

/**
 * teamCode/*from w  ww. j a  v a2s. c  o  m*/
 * @param 
 * */
@RequestMapping(params = "func=getMyTemCodes")
public void getMyTemCodes(HttpServletRequest req, HttpServletResponse resp) {
    VWBContainer container = VWBContainerImpl.findContainer();
    if (!validateRequest(req, container)) {
        resp.setStatus(401);
        return;
    }
    String uid = req.getParameter("uid");
    if (StringUtils.isEmpty(uid)) {
        resp.setStatus(400);
        return;
    }
    List<Team> myTeams = teamService.getAllUserTeams(uid);
    JSONArray teamArray = new JSONArray();
    for (Team team : myTeams) {
        if (Team.PESONAL_TEAM.equals(team.getType())) {
            continue;
        }
        teamArray.add(team.getName());
    }
    JsonUtil.writeJSONObject(resp, teamArray);

}

From source file:com.pinterest.rocksplicator.OnlineOfflineConfigGenerator.java

@Override
public void onCallback(NotificationContext notificationContext) {
    HelixAdmin admin = helixManager.getClusterManagmentTool();

    List<String> resources = admin.getResourcesInCluster(clusterName);

    Set<String> existingHosts = new HashSet<String>();

    // compose cluster config
    JSONObject config = new JSONObject();
    for (String resource : resources) {
        // Resources starting with PARTICIPANT_LEADER is for HelixCustomCodeRunner
        if (resource.startsWith("PARTICIPANT_LEADER")) {
            continue;
        }// w w  w . ja v a  2  s  . c o m

        ExternalView externalView = admin.getResourceExternalView(clusterName, resource);
        Set<String> partitions = externalView.getPartitionSet();

        // compose resource config
        JSONObject resourceConfig = new JSONObject();
        String partitionsStr = externalView.getRecord().getSimpleField("NUM_PARTITIONS");
        resourceConfig.put("num_shards", Integer.parseInt(partitionsStr));

        // build host to partition list map
        Map<String, List<String>> hostToPartitionList = new HashMap<String, List<String>>();
        for (String partition : partitions) {
            String partitionNumber = String.format("%05d", Integer.parseInt(partition.split("_")[1]));
            Map<String, String> hostToState = externalView.getStateMap(partition);
            for (Map.Entry<String, String> entry : hostToState.entrySet()) {
                if (!entry.getValue().equalsIgnoreCase("ONLINE")) {
                    continue;
                }

                existingHosts.add(entry.getKey());
                String hostWithDomain = getHostWithDomain(entry.getKey());
                List<String> partitionList = hostToPartitionList.get(hostWithDomain);
                if (partitionList == null) {
                    partitionList = new ArrayList<String>();
                    hostToPartitionList.put(hostWithDomain, partitionList);
                }

                partitionList.add(partitionNumber);
            }
        }

        // Add host to partition list map to the resource config
        for (Map.Entry<String, List<String>> entry : hostToPartitionList.entrySet()) {
            JSONArray jsonArray = new JSONArray();
            for (String p : entry.getValue()) {
                jsonArray.add(p);
            }

            resourceConfig.put(entry.getKey(), jsonArray);
        }

        // add the resource config to the cluster config
        config.put(resource, resourceConfig);
    }

    // remove host that doesn't exist in the ExternalView from hostToHostWithDomain
    hostToHostWithDomain.keySet().retainAll(existingHosts);

    String newContent = config.toString();
    if (lastPostedContent != null && lastPostedContent.equals(newContent)) {
        LOG.info("Identical external view observed, skip updating config.");
        return;
    }

    // Write the config to ZK
    LOG.info("Generating a new shard config...");

    this.dataParameters.remove("content");
    this.dataParameters.put("content", newContent);
    HttpPost httpPost = new HttpPost(this.postUrl);
    try {
        httpPost.setEntity(new StringEntity(this.dataParameters.toString()));
        HttpResponse response = new DefaultHttpClient().execute(httpPost);
        if (response.getStatusLine().getStatusCode() == 200) {
            lastPostedContent = newContent;
            LOG.info("Succeed to generate a new shard config.");
        } else {
            LOG.error(response.getStatusLine().getReasonPhrase());
        }
    } catch (Exception e) {
        LOG.error("Failed to post the new config", e);
    }
}

From source file:com.starr.smartbuilds.service.BuildService.java

public String buildData(Build build, List<Block> blocks) {
    JSONObject json_build = new JSONObject();
    json_build.put("title", build.getName());
    json_build.put("type", "custom");
    json_build.put("map", "SR");
    json_build.put("mode", "any");
    json_build.put("type", "custom");
    JSONArray json_blocks = new JSONArray();
    for (Block block : blocks) {
        JSONObject json_block = new JSONObject();
        json_block.put("type", block.getName());
        JSONArray json_items = new JSONArray();
        for (Item item : block.getItems()) {
            JSONObject json_item = new JSONObject();
            json_item.put("id", item.getId() + "");
            json_item.put("count", 1);
            json_items.add(json_item);
        }/*from w  w w  .  j a  v  a 2s .c om*/
        json_block.put("items", json_items);
        json_blocks.add(json_block);
    }
    json_build.put("blocks", json_blocks);

    return json_build.toString();
}