Example usage for org.json.simple JSONArray get

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

Introduction

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

Prototype

public E get(int index) 

Source Link

Document

Returns the element at the specified position in this list.

Usage

From source file:gamepub.beans.VKAuthorizationBean.java

public User createUser() throws IOException, ParseException, NoSuchAlgorithmException {
    String startJson = fetchPersonalInfo();
    if (!startJson.equals("")) {

        JSONParser jsonParser = new JSONParser();
        JSONObject jsonObject = (JSONObject) jsonParser.parse(startJson);
        JSONArray jsonArray = (JSONArray) jsonObject.get("response");
        JSONObject json = (JSONObject) jsonArray.get(0);
        String id = getJsonValue(json, "uid");
        //        return id;
        String nickname = "VK" + id;
        String firstName = getJsonValue(json, "first_name");
        String lastName = getJsonValue(json, "last_name");
        String name = firstName + " " + lastName;
        String photo = getJsonValue(json, "photo_max");

        Integer idLoggedUser = null;
        try {/*  ww w .  ja  va  2s  . com*/
            idLoggedUser = SessionBean.getUserId();
        } catch (Exception e) {

        }
        User user;
        if (idLoggedUser != null) {
            user = userService.getUserById(idLoggedUser);
            user.setVkInfo(id);
            userService.update(user);
        } else {

            user = new User();
            UserRole ur = userRoleService.getUserRoleById(1);
            City city = cityService.getCityById(2235395);

            user.setAvatarUrl(photo);
            String password = passwordGenerator.generatePassword(10);
            user.setPassword(shaCode.code(shaCode.code(name) + password));
            user.setEmail("default email");
            user.setActive(true);
            user.setBanned(false);
            user.setVkInfo(id);
            user.setLogin(nickname);
            user.setTradesLeft(3);
            user.setCity(city);
            user.setFine(0);
            user.setGold(false);
            user.setReputation(0);
            user.setUserRole(ur);
        }
        return user;
    }
    return null;
}

From source file:net.phyloviz.goeburst.tree.GOeBurstMSTItemFactory.java

private Map<Integer, GOeBurstNode> getNodes(Map<String, GOeBurstNode> td, JSONArray onodes) {

    Map<Integer, GOeBurstNode> nodes = new HashMap<>();
    for (Iterator<JSONObject> nIt = onodes.iterator(); nIt.hasNext();) {
        JSONObject node = nIt.next();//from   ww w  . j  ava  2  s . c  o  m
        Integer uid = (int) (long) node.get("id");
        String profile = (String) node.get("profile");
        JSONArray group_lvs = (JSONArray) node.get("group-lvs");

        GOeBurstNode n = td.get(profile);
        n.lv = new int[group_lvs.size()];
        for (int i = 0; i < group_lvs.size(); i++)
            n.lv[i] = (int) (long) group_lvs.get(i);

        nodes.put(uid, n);

    }
    return nodes;
}

From source file:com.n1t3slay3r.empirecraft.main.Update.java

/**
 * Query the API to find the latest approved file's details.
 *//*www.  ja va2 s .  co m*/
public void query() {
    URL url;

    try {
        // Create the URL to query using the project's ID
        url = new URL(API_HOST + API_QUERY + projectID);
    } catch (MalformedURLException e) {
        return;
    }

    try {
        // Open a connection and query the project
        URLConnection conn = url.openConnection();

        if (apiKey != null) {
            // Add the API key to the request if present
            conn.addRequestProperty("X-API-Key", apiKey);
        }

        // Add the user-agent to identify the program
        conn.addRequestProperty("User-Agent", "ServerModsAPI-Example (by Gravity)");

        // Read the response of the query
        // The response will be in a JSON format, so only reading one line is necessary.
        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String response = reader.readLine();

        // Parse the array of files from the query's response
        JSONArray array = (JSONArray) JSONValue.parse(response);

        if (array.size() > 0) {
            // Get the newest file's details
            JSONObject latest = (JSONObject) array.get(array.size() - 1);

            // Get the version's title
            String versionName = (String) latest.get(API_NAME_VALUE);

            // Get the version's link
            String versionLink = (String) latest.get(API_LINK_VALUE);

            // Get the version's release type
            String versionType = (String) latest.get(API_RELEASE_TYPE_VALUE);

            // Get the version's file name
            String versionFileName = (String) latest.get(API_FILE_NAME_VALUE);

            // Get the version's game version
            String versionGameVersion = (String) latest.get(API_GAME_VERSION_VALUE);

            if (playername != null) {
                Bukkit.getPlayer(UUID.fromString(playername))
                        .sendMessage(ChatColor.YELLOW + "The latest version of " + ChatColor.GOLD
                                + versionFileName + ChatColor.YELLOW + " is " + ChatColor.GOLD + versionName
                                + ChatColor.YELLOW + ", a " + ChatColor.GOLD + versionType.toUpperCase()
                                + ChatColor.YELLOW + " for " + ChatColor.GOLD + versionGameVersion
                                + ChatColor.YELLOW + ", available at: " + ChatColor.GOLD + versionLink);
            } else {
                System.out.println("The latest version of " + versionFileName + " is " + versionName + ", a "
                        + versionType.toUpperCase() + " for " + versionGameVersion + ", available at: "
                        + versionLink);
            }
        }
    } catch (IOException e) {
    }
}

From source file:control.ParametrizacionServlets.ActualizarLaboratorios.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from  ww w .j av a 2s  .  com
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    JSONObject salida = new JSONObject();
    try {
        String nombre = request.getParameter("nombre");
        String direccion = request.getParameter("direccion");
        String telefono = request.getParameter("telefono1");
        String telefono2 = request.getParameter("telefono2");
        String correo = request.getParameter("correo");
        String resolucion = request.getParameter("resolucion");
        String vigencia = request.getParameter("vigencia");
        String contactos = request.getParameter("contactos");
        Integer codigo = Integer.parseInt(request.getParameter("codigo"));
        String paramAcreditados = request.getParameter("paramAcreditados");

        Laboratorios manager = new Laboratorios();
        manager.actualizar(nombre, contactos, direccion, telefono, telefono2, correo, resolucion, vigencia,
                codigo);

        int resp = 0;
        //Obtenemos La informacion del manager
        AcreditacionParametros managerAcreditacion = new AcreditacionParametros();

        //Eliminamos lo parametros
        resp = managerAcreditacion.eliminar(codigo);

        Object obj = JSONValue.parse(paramAcreditados);
        JSONArray jsonArray = new JSONArray();
        jsonArray = (JSONArray) obj;

        //Recorremos el JSONArray y obtenemos la informacion.
        for (int i = 0; i < jsonArray.size(); i++) {

            JSONObject jsonObject = (JSONObject) jsonArray.get(i);
            int codParametro = Integer.parseInt((String) jsonObject.get("codigoParam"));

            managerAcreditacion.insertar(codParametro, codigo);

        }

    } catch (Exception e) {

    }

}

From source file:net.bashtech.geobot.JSONUtil.java

public static String lastFMURL(String user) {
    String api_key = BotManager.getInstance().LastFMAPIKey;
    String lastSong = null;//from w w  w.  j a  v a  2  s . co m
    try {
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(BotManager
                .getRemoteContent("http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=" + user
                        + "&format=json&limit=1&api_key=" + api_key));

        JSONObject jsonObject = (JSONObject) obj;

        JSONObject recenttracks = (JSONObject) (jsonObject.get("recenttracks"));
        if (recenttracks.get("track") instanceof JSONArray) {
            JSONArray track = (JSONArray) recenttracks.get("track");

            JSONObject index0 = (JSONObject) track.get(0);
            String url = (String) index0.get("url");

            return url;

        } else {
            if (lastSong == null)
                return "(Nothing)";
            else
                return lastSong;
        }
    } catch (Exception ex) {

        return "(Error querying API)";
    }

}

From source file:net.phyloviz.upgmanjcore.json.JsonSchemaValidator.java

private void createOrder(JSONArray orderObj) {
    orderList = new String[orderObj.size()];
    for (int i = 0; i < orderObj.size(); i++) {
        orderList[i] = (String) orderObj.get(i);
    }//from  w w  w .jav  a  2  s . c  om
}

From source file:com.googlecode.fascinator.portal.process.HomeInstitutionNotifier.java

/**
 * Replaces any variables in the templates using the mapping specified in
 * the config./*from   w  w  w  .j  ava2 s  .  c o  m*/
 * 
 * @param solrDoc
 * @param vars
 * @param config
 * @param context
 */
private void initVars(SolrDoc solrDoc, List<String> vars, JsonSimple config, VelocityContext context,
        String channel) {
    for (String var : vars) {
        String varField = config.getString("", channel, "mapping", var);
        String replacement = solrDoc.getString(var, varField);
        if (replacement == null || "".equals(replacement)) {
            JSONArray arr = solrDoc.getArray(varField);
            if (arr != null) {
                replacement = (String) arr.get(0);
                if (replacement == null) {
                    // giving up, setting back to source value so caller can
                    // evaluate
                    replacement = var;
                }
            } else {
                // giving up, setting back to source value so caller can
                // evaluate
                replacement = var;
            }
        }
        log.debug("Getting variable value '" + var + "' using field '" + varField + "', value:" + replacement);
        context.put(var.replace("$", ""), replacement);
    }
}

From source file:forumbox.GetUserServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/*from  w  w  w.  j  a v a  2  s .  c  om*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
// private static final long serialVersionUID = 1L;
@Override

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    JSONObject IDlistobj = null;
    JSONObject postobj = null;
    JSONParser IDlistparser = new JSONParser();
    JSONParser postParser = new JSONParser();

    String[] Idlist = new String[10];
    int count = 0;

    try {
        FileReader file1 = new FileReader(
                "/home/dinalidabarera/NetBeansProjects/NewFolder/forum4/admin01/post/list.json");

        Object obj = IDlistparser.parse(file1);

        IDlistobj = (JSONObject) obj;
        JSONArray list = (JSONArray) IDlistobj.get("list");

        count = list.size() - 1;

        for (int i = 0; i < 10 && i <= count; i++) {
            Idlist[i] = list.get(count).toString();
            count--;
        }

    } catch (Exception e) {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("get ID is unsuccessful");
        out.println(e);
        out.println("......................");
    }

    // get the posts

    try {

        String[] idlist = new String[10];
        String[] descriptionlist = new String[10];
        String[] username = new String[10];
        String[] titlelist = new String[10];

        for (int i = 0; i < 10 && i <= count; i++) {
            FileReader file = new FileReader(
                    "/home/dinalidabarera/NetBeansProjects/NewFolder/forum4/admin01/post/" + Idlist[i]
                            + ".json");
            Object obj = postParser.parse(file);
            postobj = (JSONObject) obj;
            idlist[i] = postobj.get("id").toString();
            descriptionlist[i] = postobj.get("description").toString();
            username[i] = postobj.get("username").toString();
            titlelist[i] = postobj.get("title").toString();

            if (descriptionlist[i].length() > 200) {
                descriptionlist[i] = descriptionlist[i].substring(0, 199) + "....";
            }
        }

        request.setAttribute("titlelist", titlelist);
        request.setAttribute("idlist", idlist);
        request.setAttribute("descriptionlist", descriptionlist);
        request.setAttribute("username", username);

        request.getRequestDispatcher("/indexpage.jsp").forward(request, response);

    } catch (Exception e) {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("fetching post unsuccessful");
        out.println(e);
        out.println("......................");
    }

}

From source file:net.bashtech.geobot.JSONUtil.java

public static String lastFM(String user) {
    String api_key = BotManager.getInstance().LastFMAPIKey;
    String lastSong = null;//from   w  w  w .  j a  v  a 2  s  . c o m
    try {
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(BotManager
                .getRemoteContent("http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=" + user
                        + "&format=json&limit=1&api_key=" + api_key));

        JSONObject jsonObject = (JSONObject) obj;

        JSONObject recenttracks = (JSONObject) (jsonObject.get("recenttracks"));
        if (recenttracks.get("track") instanceof JSONArray) {
            JSONArray track = (JSONArray) recenttracks.get("track");

            JSONObject index0 = (JSONObject) track.get(0);
            String trackName = (String) index0.get("name");
            JSONObject artistO = (JSONObject) index0.get("artist");
            String artist = (String) artistO.get("#text");
            lastSong = trackName + " by " + artist;
            String url = (String) index0.get("url");

            return lastSong;

        } else {
            if (lastSong == null)
                return "(Nothing)";
            else
                return lastSong;
        }
    } catch (Exception ex) {

        return "(Error querying API)";
    }

}

From source file:net.bashtech.geobot.JSONUtil.java

public static String lastSongLastFM(String user) {
    String api_key = BotManager.getInstance().LastFMAPIKey;
    String lastSong = null;//from  w  w  w  . j  a v a  2  s .c  om
    try {
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(BotManager
                .getRemoteContent("http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=" + user
                        + "&format=json&limit=2&api_key=" + api_key));

        JSONObject jsonObject = (JSONObject) obj;

        JSONObject recenttracks = (JSONObject) (jsonObject.get("recenttracks"));
        if (recenttracks.get("track") instanceof JSONArray) {
            JSONArray track = (JSONArray) recenttracks.get("track");

            JSONObject index0 = (JSONObject) track.get(1);
            String trackName = (String) index0.get("name");
            JSONObject artistO = (JSONObject) index0.get("artist");
            String artist = (String) artistO.get("#text");
            lastSong = trackName + " by " + artist;
            String url = (String) index0.get("url");

            return lastSong;

        } else {
            if (lastSong == null)
                return "(Nothing)";
            else
                return lastSong;
        }
    } catch (Exception ex) {

        return "(Error querying API)";
    }

}