Example usage for org.json.simple JSONArray JSONArray

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

Introduction

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

Prototype

JSONArray

Source Link

Usage

From source file:com.jts.rest.profileservice.utils.RestServiceHelper.java

/**
 * Gets the recent challenges and splits them to active and past challenges
 * Maximum 3 past challenges and all active challenges will be returned
 * @param sessionId//from   www.ja v  a 2 s  . c  o m
 * @param username
 * @return
 * @throws MalformedURLException
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public static JSONObject getProcessedChallengesM2(String sessionId, String username)
        throws MalformedURLException, IOException {
    JSONArray recentChallenges = getRecentParticipantChallengesByUsername(sessionId, username);
    JSONArray activeChallenges = new JSONArray();
    JSONArray pastChallenges = new JSONArray();

    Iterator<JSONObject> iterator = recentChallenges.iterator();
    while (iterator.hasNext()) {
        JSONObject participantChallenge = iterator.next();
        JSONObject challenge = (JSONObject) participantChallenge.get("Challenge__r");
        if (challenge.get("Status__c").equals(PSContants.STATUS_CREATED)) { //active challenge
            activeChallenges.add(participantChallenge);
            JSONArray categories = getCategoriesByChallenge(sessionId,
                    (String) participantChallenge.get("Challenge__c"));
            participantChallenge.put("categories", categories);
        } else { //past challenges
            if (pastChallenges.size() < 3) {
                pastChallenges.add(participantChallenge);
                JSONArray categories = getCategoriesByChallenge(sessionId,
                        (String) participantChallenge.get("Challenge__c"));
                participantChallenge.put("categories", categories);
            }
        }
    }
    JSONObject challenges = new JSONObject();
    challenges.put("activeChallenges", activeChallenges);
    challenges.put("pastChallenges", pastChallenges);
    challenges.put("totalChallenges", getChallengeCountByUser(sessionId, username));
    return challenges;
}

From source file:com.saludtec.web.TratamientosWeb.java

private JSONArray listarTratamientosPaciente(HttpServletRequest request) {
    List<Tratamientos> tratamientos = ejbTratamientos
            .listar(Integer.parseInt(request.getParameter("idPaciente")), request.getParameter("fecha"));
    objArray = new JSONArray();
    if (tratamientos != null) {
        for (Tratamientos tratamiento : tratamientos) {
            obj = new JSONObject();
            obj.put("idTratamiento", tratamiento.getIdTratamiento());
            obj.put("idPaciente", tratamiento.getIdPaciente().getIdPaciente());
            obj.put("desTratamiento", tratamiento.getDesTratamiento());
            obj.put("fechaTratamiento", tratamiento.getFechaTratamiento());
            obj.put("horaTratamiento", tratamiento.getHoraTratamiento());
            objArray.add(obj);/* w  w  w  . j ava 2 s. c  om*/
        }
    }
    return objArray;
}

From source file:edu.usc.polar.CompositeNERAgreementParser.java

public static void dir(String path, String[] args) {
    try {//  w ww  . ja  va2s  .  c om

        File root = new File(path);
        if (root.isFile()) {

            if (counter >= 1000 || file == null) {
                counter = 0;
                jsonCount++;
                file = new File(
                        "C:\\Users\\Snehal\\Documents\\tikaSimilarityTestSet\\CompositeNER\\CompositeNER_"
                                + jsonCount + ".json");
                if (jsonFile != null) {
                    jsonFile.write("{\"CompositeNER\":");
                    jsonFile.write(jsonArray.toJSONString());
                    jsonFile.write("}");
                    //System.out.println(jsonArray.toJSONString());
                    jsonFile.close();
                }
                jsonFile = new FileWriter(file);
                jsonArray = new JSONArray();
            }

            if (!root.getName().equals((".DS_Store"))) {
                CompositeNER(root.getAbsolutePath(), args);
                counter++;
            }
        } else {
            File[] list = root.listFiles();
            if (list == null) {
                return;
            }
            for (File f : list) {
                if (f.isDirectory()) {
                    dir(f.getAbsolutePath(), args);
                    System.out.println("Dir:" + f.getAbsoluteFile());
                } else {
                    if (counter >= 1000 || file == null) {
                        counter = 0;
                        jsonCount++;
                        file = new File(
                                "C:\\Users\\Snehal\\Documents\\tikaSimilarityTestSet\\CompositeNER\\CompositeNER_"
                                        + jsonCount + ".json");
                        // System.out.print("check"+jsonArray.toJSONString());
                        if (jsonFile != null) {
                            jsonFile.write("{\"CompositeNER\":");
                            jsonFile.write(jsonArray.toJSONString());
                            jsonFile.write("}");
                            //System.out.println(jsonArray.toJSONString());
                            jsonFile.close();
                        }
                        jsonFile = new FileWriter(file);
                        jsonArray = new JSONArray();
                    }

                    if (!f.getName().equals((".DS_Store"))) {
                        CompositeNER(f.getAbsolutePath(), args);
                        counter++;
                        // add json   
                    }
                }
            }
        }
    } catch (Exception e) {
        e.toString();

    }
}

From source file:com.aerothai.database.user.UserService.java

public JSONObject GetUserAt(int id) throws Exception {

    ArrayList<UserObj> feeds = new ArrayList<UserObj>();
    Connection dbConn = null;/*from  ww  w .  j a v  a 2s.com*/
    JSONObject obj = new JSONObject();
    JSONArray objList = new JSONArray();

    int no = 1;
    obj.put("tag", "listat");
    obj.put("msg", "error");
    obj.put("status", false);
    try {
        dbConn = DBConnection.createConnection();

        Statement stmt = dbConn.createStatement();
        String query = "SELECT * FROM user,dept where user.iddept = dept.iddept AND user.iduser = " + id;
        System.out.println(query);
        ResultSet rs = stmt.executeQuery(query);

        while (rs.next()) {

            JSONObject jsonData = new JSONObject();
            jsonData.put("iduser", rs.getInt("iduser"));
            jsonData.put("name", rs.getString("name"));
            jsonData.put("lastname", rs.getString("lastname"));
            jsonData.put("idposition", rs.getInt("idposition"));
            jsonData.put("iddept", rs.getInt("iddept"));
            ;
            jsonData.put("idunit", rs.getInt("idunit"));
            jsonData.put("idrole", rs.getInt("idrole"));
            jsonData.put("address", rs.getString("address"));
            jsonData.put("email", rs.getString("email"));
            jsonData.put("tel", rs.getString("tel"));
            jsonData.put("actunit", rs.getString("actunit"));
            jsonData.put("username", rs.getString("username"));
            jsonData.put("namedept", rs.getString("dept.name"));
            jsonData.put("shortdept", rs.getString("shortname"));
            jsonData.put("photo", rs.getString("photo"));
            jsonData.put("actcust", rs.getString("actcust"));
            jsonData.put("no", no);
            objList.add(jsonData);
            no++;
        }
        obj.put("msg", "done");
        obj.put("status", true);
        obj.put("data", objList);
    } catch (SQLException sqle) {
        throw sqle;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        if (dbConn != null) {
            dbConn.close();
        }
        throw e;
    } finally {
        if (dbConn != null) {
            dbConn.close();
        }
    }
    return obj;
}

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  w  w.  j  av  a2 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:com.juniform.JUniformPackerJSON.java

@SuppressWarnings("unchecked")
private Object _toJSON(JUniformObject object) {
    if (object == null) {
        return null;
    } else if (object.isMapValue()) {
        JSONObject jsonMap = new JSONObject();
        Iterator<Map.Entry<Object, JUniformObject>> it = object.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<Object, JUniformObject> pair = it.next();
            jsonMap.put(pair.getKey(), this._toJSON(pair.getValue()));
        }//from  w  w w  .  j  a  v a 2 s. c  om
        return jsonMap;

    } else if (object.isArrayValue()) {
        JSONArray jsonArray = new JSONArray();

        Iterator<JUniformObject> it = object.iterator();
        while (it.hasNext()) {
            jsonArray.add(this._toJSON(it.next()));
        }
        return jsonArray;
    } else {
        return object.getValue();
    }
}

From source file:at.uni_salzburg.cs.ckgroup.cscpp.engine.parser.Task.java

@SuppressWarnings("unchecked")
@Override//from   w w  w .j a v  a  2  s  .co m
public String toJSONString() {

    JSONObject obj = new JSONObject();
    obj.put("point", getPosition());
    obj.put("tolerance", getTolerance());
    // TODO arrival time, delay, and lifetime in JSON string?

    JSONArray act = new JSONArray();
    for (IAction a : getActionList()) {
        act.add(a);
    }
    obj.put("actions", act);

    return obj.toJSONString();
}

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);//from ww  w.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:ApplicationIntegrationTest.java

@Test
public void test1CanCreateBook() {

    //System.out.println("\n\n\nBOOK:" + _bookDTO.getId() + ":" + _bookDTO.getTitle() + "\n\n\n");
    //_userDTO = _userService.readOne(1);

    _genreDTO1 = _genreService.create(_genreDTO1);
    _subgenreDTO1 = _subgenreService.create(_subgenreDTO1);
    _themeDTO1 = _themeService.create(_themeDTO1);
    _awardDTO1 = _awardService.create(_awardDTO1);
    _formatDTO1 = _formatService.create(_formatDTO1);
    _miscDTO1 = _miscService.create(_miscDTO1);

    JSONObject userJson = new JSONObject();
    userJson.put("id", _userDTO.getId());
    userJson.put("username", _userDTO.getUsername());

    JSONObject genreJson = new JSONObject();
    genreJson.put("id", _genreDTO1.getId());
    JSONArray genreDTOs = new JSONArray();
    genreDTOs.add(genreJson);/*  ww  w. ja  v  a 2  s.com*/

    JSONObject subgenreJson = new JSONObject();
    subgenreJson.put("id", _subgenreDTO1.getId());
    JSONArray subgenreDTOs = new JSONArray();
    subgenreDTOs.add(subgenreJson);

    JSONObject themeJson = new JSONObject();
    themeJson.put("id", _themeDTO1.getId());
    JSONArray themeDTOs = new JSONArray();
    themeDTOs.add(themeJson);

    JSONObject awardJson = new JSONObject();
    awardJson.put("id", _awardDTO1.getId());
    JSONArray awardDTOs = new JSONArray();
    awardDTOs.add(awardJson);

    JSONObject formatJson = new JSONObject();
    formatJson.put("id", _formatDTO1.getId());
    JSONArray formatDTOs = new JSONArray();
    formatDTOs.add(formatJson);

    JSONObject miscJson = new JSONObject();
    miscJson.put("id", _miscDTO1.getId());
    JSONArray miscDTOs = new JSONArray();
    miscDTOs.add(miscJson);

    JSONObject bookJson = new JSONObject();
    bookJson.put("title", _bookDTO.getTitle());
    bookJson.put("author", _bookDTO.getAuthor());
    bookJson.put("publisher", _bookDTO.getPublisher());
    bookJson.put("isbn", _bookDTO.getIsbn());
    bookJson.put("year", _bookDTO.getYear());
    bookJson.put("user", userJson);

    bookJson.put("genres", genreDTOs);
    bookJson.put("subgenres", subgenreDTOs);
    bookJson.put("themes", themeDTOs);
    bookJson.put("awards", awardDTOs);
    bookJson.put("formats", formatDTOs);
    bookJson.put("misc", miscDTOs);

    System.out.println("\n\n\n\nJSON: \n" + bookJson.toJSONString());
    System.out.println("\nJSON: \n" + genreDTOs.toJSONString() + "\n\n\n\n");

    Integer bookId = given().contentType(JSON).body(bookJson.toJSONString()).when().post("/createBook").then()
            .contentType(JSON).statusCode(HttpStatus.SC_OK).body("title", equalTo(_bookDTO.getTitle()))
            .body("author", equalTo(_bookDTO.getAuthor())).body("publisher", equalTo(_bookDTO.getPublisher()))
            .body("isbn", equalTo(_bookDTO.getIsbn())).body("year", equalTo(_bookDTO.getYear())).

            body("genres[0].name", equalTo(_genreDTO1.getName()))
            .body("genres[0].description", equalTo(_genreDTO1.getDescription())).

            body("subgenres[0].name", equalTo(_subgenreDTO1.getName()))
            .body("subgenres[0].description", equalTo(_subgenreDTO1.getDescription())).

            body("themes[0].name", equalTo(_themeDTO1.getName()))
            .body("themes[0].description", equalTo(_themeDTO1.getDescription())).

            body("awards[0].name", equalTo(_awardDTO1.getName()))
            .body("awards[0].description", equalTo(_awardDTO1.getDescription())).

            body("formats[0].name", equalTo(_formatDTO1.getName()))
            .body("formats[0].description", equalTo(_formatDTO1.getDescription())).

            body("misc[0].name", equalTo(_miscDTO1.getName()))
            .body("misc[0].description", equalTo(_miscDTO1.getDescription())).

            log().ifError().extract().path("id");

    _bookDTO.setId(bookId);

    //System.out.println("\n\n\n **" + bookId + "**\n\n\n");
    System.out.println("\n\n\n\n CREATED BOOK: \n"
            + get("/readBook?id=".concat(_bookDTO.getId().toString())).asString() + "\n\n\n\n");

}