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:di.uniba.it.tee2.api.v1.SearchService.java

@GET
public Response search(@QueryParam("contextQuery") String query, @QueryParam("timeQuery") String timeQuery,
        @QueryParam("n") int n) {
    try {//from www  .j av  a 2 s .com
        SearchServiceWrapper instance = SearchServiceWrapper.getInstance(
                ServerConfig.getInstance().getProperty("search.language"),
                ServerConfig.getInstance().getProperty("search.index"));
        List<SearchResult> search = instance.getSearch().search(query, timeQuery, n);
        JSONObject json = new JSONObject();
        json.put("size", search.size());
        JSONArray results = new JSONArray();
        for (SearchResult sr : search) {
            results.add(sr.toJSON());
        }
        json.put("results", results);
        return Response.ok(json.toString()).build();
    } catch (Exception ex) {
        Logger.getLogger(SearchService.class.getName()).log(Level.SEVERE, null, ex);
        return Response.serverError().build();
    }
}

From source file:com.avatarproject.core.storage.UserCache.java

/**
 * Adds a player into the custom UserCache.
 * @param player Player to add to the cache.
 *///from   w  ww . j  av a 2 s . c  o m
@SuppressWarnings("unchecked")
public static void addUser(Player player) {
    String name = player.getName();
    UUID uuid = player.getUniqueId();
    JSONArray array = getUserCache();
    try {
        for (int n = 0; n < array.size(); n++) { //Loop through all the objects in the array.
            JSONObject object = (JSONObject) array.get(n);
            if (object.get("id").equals(uuid.toString())) { //Check if the player's UUID exists in the cache.
                if (String.valueOf(object.get("name")).equalsIgnoreCase(name)) {
                    return;
                } else {
                    object.put("name", name); //Update the user.
                    FileWriter fileOut = new FileWriter(usercache);
                    fileOut.write(array.toJSONString()); //Write the JSON array to the file.
                    fileOut.close();
                    return;
                }
            }
        }
        JSONObject newEntry = new JSONObject();
        newEntry.put("id", uuid.toString());
        newEntry.put("name", name);
        array.add(newEntry); //Add a new player into the cache.
        FileWriter fileOut = new FileWriter(usercache);
        fileOut.write(array.toJSONString()); //Write the JSON array to the file.
        fileOut.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Activities.java

private String addData(String endpoint) {
    String data = null;/*from   ww w. j  a  v a2  s .  c  o  m*/
    try {
        // Construct request payload
        JSONObject attrObj = new JSONObject();
        attrObj.put("name", "URL");
        attrObj.put("value", "http://www.nvidia.com/game-giveaway");

        JSONArray attrArray = new JSONArray();
        attrArray.add(attrObj);

        TimeZone tz = TimeZone.getTimeZone("UTC");
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
        df.setTimeZone(tz);
        String dateAsISO = df.format(new Date());

        // Required attributes
        JSONObject obj = new JSONObject();
        obj.put("leadId", "1001");
        obj.put("activityDate", dateAsISO);
        obj.put("activityTypeId", "1001");
        obj.put("primaryAttributeValue", "Game Giveaway");
        obj.put("attributes", attrArray);
        System.out.println(obj);

        // Make request
        URL url = new URL(endpoint);
        HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
        urlConn.setRequestMethod("POST");
        urlConn.setAllowUserInteraction(false);
        urlConn.setDoOutput(true);
        urlConn.setRequestProperty("Content-type", "application/json");
        urlConn.setRequestProperty("accept", "application/json");
        urlConn.connect();
        OutputStream os = urlConn.getOutputStream();
        os.write(obj.toJSONString().getBytes());
        os.close();

        // Inspect response
        int responseCode = urlConn.getResponseCode();
        if (responseCode == 200) {
            System.out.println("Status: 200");
            InputStream inStream = urlConn.getInputStream();
            data = convertStreamToString(inStream);
            System.out.println(data);
        } else {
            System.out.println(responseCode);
            data = "Status:" + responseCode;
        }
    } catch (MalformedURLException e) {
        System.out.println("URL not valid.");
    } catch (IOException e) {
        System.out.println("IOException: " + e.getMessage());
        e.printStackTrace();
    }

    return data;
}

From source file:com.mobicage.rogerthat.form.AbstractSelectWidget.java

@Override
@SuppressWarnings("unchecked")
public JSONObject toJSONObject() {
    JSONObject result = new JSONObject();
    JSONArray choicesArray = new JSONArray();
    for (Choice choice : choices) {
        choicesArray.add(choice.toJSONObject());
    }/*from  w ww.  j a v  a2s. c  o m*/
    result.put("choices", choicesArray);
    return result;
}

From source file:me.m0r13.maptools.MarkerUpdateTask.java

public void writePlayers(Player[] players) {
    JSONArray playersJson = new JSONArray();
    for (Player player : players) {
        JSONObject json = new JSONObject();

        Location pos = player.getLocation();
        World world = player.getWorld();

        json.put("username", player.getName());
        json.put("x", pos.getX());
        json.put("y", pos.getY());
        json.put("z", pos.getZ());
        json.put("world", world.getName());
        json.put("dimension", world.getEnvironment().toString());
        json.put("health", player.getHealth());
        json.put("saturation", player.getSaturation());
        json.put("food", player.getFoodLevel());
        Location bed = player.getBedSpawnLocation();
        if (bed == null) {
            json.put("bed", null);
        } else {/*  w  w w .j ava 2  s  .c o m*/
            JSONArray bedJson = new JSONArray();
            bedJson.add(bed.getBlockX());
            bedJson.add(bed.getBlockY());
            bedJson.add(bed.getBlockZ());
            json.put("bed", bedJson);
        }
        json.put("level", (float) player.getLevel() + player.getExp());
        playersJson.add(json);
    }
    JSONObject json = new JSONObject();
    json.put("players", playersJson);

    try {
        File file = new File(plugin.getConfig().getString("markerFile"));
        BufferedWriter output = new BufferedWriter(new FileWriter(file));
        output.write(json.toJSONString());
        output.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:ab.server.Proxy.java

@SuppressWarnings("unchecked")
public synchronized <T> T send(ProxyMessage<T> message) {
    //Long t1 = System.nanoTime();
    JSONArray a = new JSONArray();
    a.add(id);
    a.add(message.getMessageName());//from w  ww  .java  2s.co  m
    a.add(message.getJSON());

    ProxyResult<T> result = new ProxyResult<T>();
    result.message = message;
    results.put(id, result);

    for (WebSocket conn : connections()) {
        conn.send(a.toJSONString());
    }

    id++;

    try {

        return (T) result.queue.take();
    } catch (InterruptedException e) {

        e.printStackTrace();
    }
    return null;
}

From source file:com.bigml.histogram.Bin.java

@SuppressWarnings("unchecked")
public JSONArray toJSON(DecimalFormat format) {
    JSONArray binJSON = new JSONArray();
    binJSON.add(Utils.roundNumber(_mean, format));
    binJSON.add(Utils.roundNumber(_count, format));
    _target.addJSON(binJSON, format);/* ww w  . ja va 2  s  . co m*/
    return binJSON;
}

From source file:kjscompiler.Settings.java

public Settings(String path) throws ParseException, FileNotFoundException, IOException {
    JSONParser parser = new JSONParser();
    File file = new File(path);
    String parent = file.exists() ? file.getParent() : null;
    File dir = new File(null == parent || parent.isEmpty() ? "." : parent);
    FileReader fr = new FileReader(file);
    char[] fileData = new char[(int) file.length()];
    fr.read(fileData);// ww  w .j a va 2 s  .c o  m
    String content = new String(fileData);
    JSONObject obj = (JSONObject) parser.parse(content);
    if (obj.get("basedir") instanceof JSONArray) {
        this.baseDir = (JSONArray) obj.get("basedir");
    } else {
        JSONArray arr = new JSONArray();
        arr.add(obj.get("basedir"));
        this.baseDir = arr;
    }
    this.output = (String) obj.get("output");
    this.level = (String) obj.get("level");
    this.pattern = (String) obj.get("pattern");
    this.wrapper = obj.get("wrapper") != null ? (String) obj.get("wrapper") : "";
    this.projectPath = dir.getCanonicalPath();

    dir = new File(this.projectPath, this.output);
    this.output = dir.getCanonicalPath();

    fr.close();
}

From source file:com.mobicage.rogerthat.form.LongListWidgetResult.java

@SuppressWarnings("unchecked")
@Override/*from  www  . j  av a  2  s .  c o  m*/
public JSONObject toJSONObject() {
    JSONObject obj = new JSONObject();
    if (this.values == null)
        obj.put("values", null);
    else {
        JSONArray array = new JSONArray();
        for (Long val : this.values) {
            array.add(val);
        }
        obj.put("values", array);
    }
    return obj;
}

From source file:com.owly.srv.BasicDataMetricInJson.java

/**
 * This method will add  a new json array with values the date in epoch mode, and the value capured. This the way flot pluggin in juqery wants the data.
 * @param dateOfValue is the time where the metrics was captures
 * @param Value is the value captured//from  www . ja v a2  s.  c o  m
 */
public void addJsonDataArray(Date dateOfValue, float Value) {

    JSONArray jsonArray = new JSONArray();
    jsonArray.add(dateOfValue.getTime());
    jsonArray.add(Value);
    this.jsonDataArray.add(jsonArray);

}