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.saludtec.web.EvolucionComentariosWeb.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        String servicio = request.getRequestURI().replace("/HCEMed/EvolucionComentarios/", "");
        switch (servicio) {
        case "guardar":
            guardarEvolucionComentario(request).writeJSONString(out);
            break;

        case "listar":
            listarEvolucionComentario(request).writeJSONString(out);
            break;

        default:/*from  w  w w.j  a v a  2s.  co  m*/
            obj = new JSONObject();
            objArray = new JSONArray();
            obj.put("error", "404 - El servicio " + servicio + " no existe");
            objArray.add(obj);
            objArray.writeJSONString(out);
            break;
        }
    }
}

From source file:bookUtilities.BookSearchServlet.java

private JSONArray getSearchResults(String searchPhrase) {
    JSONArray booksToReturn = new JSONArray();
    try {/*w  w w  . ja v a  2 s .co m*/
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

        Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost;user=sa;password=nopw");

        Statement st = con.createStatement();
        if (searchPhrase.equals("newest")) {
            String query = "SELECT * " + "FROM [HardCover].[dbo].[Book] " + "WHERE Active = 1 "
                    + "ORDER BY DateAdded DESC;";

            ResultSet rs = st.executeQuery(query);
            while (rs.next()) {
                String bookId = rs.getString("BookUuid");
                Statement st2 = con.createStatement();
                query = "SELECT AuthorName " + "FROM [HardCover].[dbo].[Author] " + "WHERE BookId = '" + bookId
                        + "';";
                ResultSet rs2 = st2.executeQuery(query);
                String authors = "";
                while (rs2.next()) {
                    if (authors.isEmpty()) {
                        authors = rs2.getString("AuthorName");
                    } else {
                        authors = authors + ", " + rs2.getString("AuthorName");
                    }
                }
                Statement st3 = con.createStatement();
                query = "SELECT Genre " + "FROM [HardCover].[dbo].[Genre] " + "WHERE BookId = '" + bookId
                        + "';";
                ResultSet rs3 = st3.executeQuery(query);
                String genres = "";
                while (rs3.next()) {
                    if (genres.isEmpty()) {
                        genres = rs3.getString("Genre");
                    } else {
                        genres = genres + ", " + rs3.getString("Genre");
                    }
                }
                JSONObject bookToAdd = new JSONObject();
                bookToAdd.put("bookId", bookId);
                bookToAdd.put("numCopies", rs.getString("NumCopies"));
                bookToAdd.put("title", rs.getString("Title"));
                bookToAdd.put("cover", rs.getString("Cover"));
                bookToAdd.put("author", authors);
                bookToAdd.put("genres", genres);
                booksToReturn.add(bookToAdd);
            }
        } else if (searchPhrase.equals("popular")) {
            String query = "SELECT * " + "FROM [HardCover].[dbo].[Book] " + "WHERE Active = 1 "
                    + "ORDER BY TimesBorrowed DESC;";

            ResultSet rs = st.executeQuery(query);
            while (rs.next()) {
                String bookId = rs.getString("BookUuid");
                Statement st2 = con.createStatement();
                query = "SELECT AuthorName " + "FROM [HardCover].[dbo].[Author] " + "WHERE BookId = '" + bookId
                        + "';";
                ResultSet rs2 = st2.executeQuery(query);
                String authors = "";
                while (rs2.next()) {
                    if (authors.isEmpty()) {
                        authors = rs2.getString("AuthorName");
                    } else {
                        authors = authors + ", " + rs2.getString("AuthorName");
                    }
                }
                Statement st3 = con.createStatement();
                query = "SELECT Genre " + "FROM [HardCover].[dbo].[Genre] " + "WHERE BookId = '" + bookId
                        + "';";
                ResultSet rs3 = st3.executeQuery(query);
                String genres = "";
                while (rs3.next()) {
                    if (genres.isEmpty()) {
                        genres = rs3.getString("Genre");
                    } else {
                        genres = genres + ", " + rs3.getString("Genre");
                    }
                }
                JSONObject bookToAdd = new JSONObject();
                bookToAdd.put("bookId", bookId);
                bookToAdd.put("numCopies", rs.getString("NumCopies"));
                bookToAdd.put("title", rs.getString("Title"));
                bookToAdd.put("cover", rs.getString("Cover"));
                bookToAdd.put("author", authors);
                bookToAdd.put("genres", genres);
                booksToReturn.add(bookToAdd);
            }
        } else {
            String query = "SELECT * " + "FROM HardCover.dbo.Book JOIN HardCover.dbo.Author "
                    + "ON HardCover.dbo.Book.BookUuid = HardCover.dbo.Author.BookId "
                    + "JOIN HardCover.dbo.Genre ON HardCover.dbo.Book.BookUuid = HardCover.dbo.Genre.BookId "
                    + "WHERE (FREETEXT((Title, Publisher, BookDescription, BookLanguage), '" + searchPhrase
                    + "') OR FREETEXT(AuthorName,'" + searchPhrase + "') OR FREETEXT(Genre,'" + searchPhrase
                    + "')) AND Active = 1 " + " ORDER BY Title;";

            ResultSet rs = st.executeQuery(query);
            String oldTitle = "";
            String oldAuthor = "";
            String oldGenre = "";
            while (rs.next()) {
                JSONObject bookToAdd = new JSONObject();
                String newTitle = rs.getString("Title");
                String newAuthor = rs.getString("AuthorName");
                String newGenre = rs.getString("Genre");
                if (oldTitle.equals(newTitle)) {
                    if (!(oldAuthor.equals(newAuthor))) {
                        bookToAdd = ((JSONObject) booksToReturn.remove(booksToReturn.size() - 1));
                        bookToAdd.put("author", bookToAdd.get("author") + ", " + newAuthor);
                        oldAuthor = newAuthor;
                        booksToReturn.add(bookToAdd);
                    } else if (!(oldGenre.equals(newGenre))) {
                        bookToAdd = ((JSONObject) booksToReturn.remove(booksToReturn.size() - 1));
                        bookToAdd.put("genres", bookToAdd.get("genres") + ", " + newGenre);
                        oldGenre = newGenre;
                        booksToReturn.add(bookToAdd);
                    }
                } else {
                    bookToAdd.put("bookId", rs.getString("BookUuid"));
                    bookToAdd.put("numCopies", rs.getString("NumCopies"));
                    bookToAdd.put("title", newTitle);
                    bookToAdd.put("cover", rs.getString("Cover"));
                    bookToAdd.put("author", newAuthor);
                    bookToAdd.put("genres", newGenre);
                    oldTitle = newTitle;
                    oldAuthor = newAuthor;
                    oldGenre = newGenre;
                    booksToReturn.add(bookToAdd);
                }
            }
        }

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    return booksToReturn;
}

From source file:com.Assignment4.Prod.java

/**
 * Retrieves representation of an instance of com.oracle.products.ProductResource
 * @return an instance of java.lang.String
 *///from w  w w.  jav  a  2 s  . c  o m
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getAllProducts() throws SQLException {
    if (connect == null) {
        return "not connected";
    } else {
        String query = "Select * from product";
        PreparedStatement preparedst = connect.prepareStatement(query);
        ResultSet rs = preparedst.executeQuery();
        String result = "";
        JSONArray productArr = new JSONArray();
        while (rs.next()) {
            Map pMap = new LinkedHashMap();
            pMap.put("productID", rs.getInt("product_id"));
            pMap.put("name", rs.getString("name"));
            pMap.put("description", rs.getString("description"));
            pMap.put("quantity", rs.getInt("quantity"));
            productArr.add(pMap);
        }
        result = productArr.toString();
        return result.replace("},", "},\n");
    }

}

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()));
    }//w  ww. ja va  2s . c om

    return data;
}

From source file:com.imagelake.android.usersmanagement.Servlet_UserManagement.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    PrintWriter out = response.getWriter();
    try {/*from  ww w .j  a  v  a 2 s  . c om*/

        String type = request.getParameter("type");
        JSONArray ja;
        if (type != null && !type.trim().equals("")) {

            if (type.equals("all")) {
                ja = new JSONArray();
                List<User> li = udi.listSellersBuyers();
                if (!li.isEmpty()) {

                    for (User u : li) {
                        JSONObject jo = new JSONObject();
                        jo.put("id", u.getUser_id());
                        jo.put("user_name", u.getUser_name());
                        jo.put("f_name", u.getFirst_name());
                        jo.put("l_name", u.getLast_name());
                        jo.put("em", u.getEmail());
                        jo.put("phn", u.getPhone());
                        jo.put("state", u.getState());
                        jo.put("type", u.getUser_type());
                        ja.add(jo);
                    }
                    out.write("json=" + ja.toJSONString());
                } else {
                    out.write("msg=No item found.");
                }
            } else if (type.equals("sort")) {
                ja = new JSONArray();

                String uid, date, buy, sell, name;
                uid = request.getParameter("uid");
                date = request.getParameter("date");
                buy = request.getParameter("buy");
                sell = request.getParameter("sell");
                name = request.getParameter("name");

                System.out.println("uid:" + uid);
                System.out.println("date:" + date);
                System.out.println("buy:" + buy);
                System.out.println("sell:" + sell);

                String sql = "SELECT * FROM user WHERE ";

                if (!sell.equals("false") || !buy.equals("false")) {

                    if (!uid.equals("") && !uid.equals(null)) {
                        System.out.println("user id=" + uid);
                        sql += " user_id='" + Integer.parseInt(uid) + "'";
                        if (!date.trim().equals("") && !date.equals(null)
                                || !buy.equals("") && !buy.equals(null)
                                || !sell.equals("") && !sell.equals(null)
                                || !name.equals("") && !name.equals(null)) {
                            sql += " AND ";
                        }
                    }
                    if (!date.equals("") && !date.equals(null)) {
                        String[] dt = date.split("-");
                        String orDate = dt[2] + "-" + dt[1] + "-" + dt[0];
                        System.out.println("date=" + orDate);

                        sql += " date='" + orDate + "'";
                        if (!buy.equals("") && !buy.equals(null) || !sell.equals("") && !sell.equals(null)
                                || !name.equals("") && !name.equals(null)) {
                            sql += " AND ";
                        }

                    }

                    //                    if (!name.equals("") && !name.equals(null)) {
                    //                        System.out.println("Name=" + name);
                    //                        sql += "user_name='" + name + "'";
                    //                        if (!buy.equals("") && !buy.equals(null) || !sell.equals("") && !sell.equals(null)) {
                    //                            sql += " AND ";
                    //                        }
                    //                    }
                    if (!buy.equals("") && !buy.equals(null) && !buy.equals("false")) {
                        System.out.println("buyers=" + buy);
                        sql += "user_type_user_type_id='" + 3 + "'";
                        if (!sell.equals("") && !sell.equals(null) && !sell.equals("false")) {
                            sql += " OR ";
                        }

                    }
                    if (!sell.equals("") && !sell.equals(null) && !sell.equals("false")) {
                        System.out.println("Sellers=" + sell);
                        sql += "user_type_user_type_id='" + 2 + "'";

                    }
                    System.out.println("sql=" + sql);
                    PreparedStatement ps;

                    try {
                        ps = DBFactory.getConnection().prepareStatement(sql);
                        ResultSet rs = ps.executeQuery();
                        while (rs.next()) {
                            JSONObject jo = new JSONObject();
                            jo.put("id", rs.getInt(1));
                            jo.put("user_name", rs.getString(2));
                            jo.put("f_name", rs.getString(3));
                            jo.put("l_name", rs.getString(4));
                            jo.put("em", rs.getString(5));
                            jo.put("phn", rs.getString(12));
                            jo.put("state", rs.getInt(19));
                            jo.put("type", rs.getInt(21));
                            ja.add(jo);
                        }

                        out.write("json=" + ja.toJSONString());
                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("error sql");
                        out.write("msg=Internal server error,Please try again later.");
                    }

                } else {
                    System.out.println("no item");
                    out.write("msg=No item found.");
                }
            } else if (type.equals("update")) {
                String id = request.getParameter("id");
                String uid = request.getParameter("uid");
                String state = request.getParameter("state");

                System.out.println("id:" + id);
                System.out.println("uid:" + uid);
                System.out.println("state:" + state);

                String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                        .format(Calendar.getInstance().getTime());

                User user = (User) udi.getUser(Integer.parseInt(uid));

                boolean ok = udi.updateUserState(Integer.parseInt(uid), Integer.parseInt(state));
                String un = udi.getUn(Integer.parseInt(uid));
                if (ok) {
                    //                        AdminNotification a = new AdminNotification();
                    //                        a.setUser_id(user.getUser_id());
                    //                        a.setDate(timeStamp);
                    //
                    //                        a.setShow(1);
                    //                        if (state.equals("2")) {
                    //                            a.setType(2);
                    //                            String not = "Admin " + user.getUser_name() + " has blocked user " + un;
                    //                            a.setNotification(not);
                    //                        } else if (state.equals("1")) {
                    //                            a.setType(4);
                    //                            String not = "Admin " + user.getUser_name() + " has activated user " + un;
                    //                            a.setNotification(not);
                    //                        }
                    //
                    //                        int an = new AdminNotificationDAOImp().insertNotificaation(a);
                    //                        System.out.println("PPPPPPPPPPPPPPPPPPPPPPPPPPPPPP " + an);
                    //
                    //                        boolean kl = new AdminHasNotificationDAOImp().insertNotification(udi.notMeList(user.getUser_id()), an, 1);
                    //                        if (kl) {
                    //                            out.write("ok");
                    //                        } else {
                    //                            out.write("no");
                    //                        }
                    out.write("msg=Successful...");
                } else {
                    out.write("msg=Unable to complete the action,Please try agin later.");
                }

            }

        } else {
            System.out.println("type");
            out.write("msg=Internal server error,Please try again later.");
        }

    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("error");
        out.write("msg=Internal server error,Please try again later.");
    }

}

From source file:com.telefonica.iot.cygnus.utils.CommonUtilsForTests.java

/**
 * Creates a JSONObject-like notification.
 * @return A JSONObject-like notification
 *//*  www .j  a va2  s.  c  o  m*/
public static JSONObject createNotification() {
    JSONObject attribute = new JSONObject();
    attribute.put("name", "temperature");
    attribute.put("type", "centigrade");
    attribute.put("value", "26.5");
    JSONArray attributes = new JSONArray();
    attributes.add(attribute);
    JSONObject contextElement = new JSONObject();
    contextElement.put("attributes", attributes);
    contextElement.put("type", "Room");
    contextElement.put("isPattern", "false");
    contextElement.put("id", "room1");
    JSONObject statusCode = new JSONObject();
    statusCode.put("code", "200");
    statusCode.put("reasonPhrase", "OK");
    JSONObject contextResponse = new JSONObject();
    contextResponse.put("contextElement", contextElement);
    contextResponse.put("statusCode", statusCode);
    JSONArray contextResponses = new JSONArray();
    contextResponses.add(contextResponse);
    JSONObject notification = new JSONObject();
    notification.put("subscriptionId", "51c0ac9ed714fb3b37d7d5a8");
    notification.put("originator", "localhost");
    notification.put("contextResponses", contextResponses);
    return notification;
}

From source file:mml.handler.get.MMLGetVersionsHandler.java

/**
 * Get the version listing from the MVD/*from www.  j a va2s . c  o  m*/
 * @param request the request
 * @param response the response
 * @param urn the remaining urn being empty
 * @throws MMLException 
 */
public void handle(HttpServletRequest request, HttpServletResponse response, String urn) throws MMLException {
    try {
        String docid = request.getParameter(Params.DOCID);
        if (docid == null)
            throw new Exception("You must specify a docid parameter");
        AeseResource res = doGetResource(Database.CORTEX, docid);
        JSONArray jVersions = new JSONArray();
        if (res != null) {
            String[] versions = res.listVersions();
            HashMap<String, JSONObject> vSet = new HashMap<String, JSONObject>();
            for (int i = 0; i < versions.length; i++) {
                String base = Layers.stripLayer(versions[i]);
                JSONObject jObj = vSet.get(base);
                if (jObj == null)
                    jObj = new JSONObject();
                String upgraded = Layers.upgradeLayerName(versions, versions[i]);
                if (!upgraded.equals(versions[i])) {
                    JSONArray repl = (JSONArray) jObj.get("replacements");
                    if (repl == null) {
                        repl = new JSONArray();
                        jObj.put("replacements", repl);
                    }
                    JSONObject entry = new JSONObject();
                    entry.put("old", versions[i]);
                    entry.put("new", upgraded);
                    repl.add(entry);
                }
                if (upgraded.endsWith("layer-final"))
                    jObj.put("desc", res.getVersionLongName(i + 1));
                // add the layer names
                if (upgraded.endsWith("layer-final") || upgraded.matches(".*layer-[0-9]+$")) {
                    JSONArray jArr = (JSONArray) jObj.get("layers");
                    if (jArr == null)
                        jArr = new JSONArray();
                    int index = upgraded.lastIndexOf("layer");
                    String layerName = upgraded.substring(index);
                    if (!jArr.contains(layerName))
                        jArr.add(layerName);
                    if (!jObj.containsKey("layers"))
                        jObj.put("layers", jArr);
                }
                if (!vSet.containsKey(base))
                    vSet.put(base, jObj);
            }
            // convert hashmap to array
            Set<String> keys = vSet.keySet();
            Iterator<String> iter = keys.iterator();
            while (iter.hasNext()) {
                String version = iter.next();
                JSONObject jObj = vSet.get(version);
                jObj.put("vid", version);
                jVersions.add(jObj);
            }
        }
        response.setContentType("application/json");
        response.setCharacterEncoding(encoding);
        String jStr = jVersions.toJSONString().replaceAll("\\\\/", "/");
        response.getWriter().println(jStr);
    } catch (Exception e) {
        throw new MMLException(e);
    }
}

From source file:at.uni_salzburg.cs.ckgroup.cscpp.mapper.json.MapperStatusQuery.java

@SuppressWarnings("unchecked")
public String execute(IServletConfig config, String[] parameters) {

    if (mapper == null) {
        return "";
    }/*ww  w . j a v a 2s  . c o  m*/

    Map<String, IRegistrationData> registrationData = mapper.getRegistrationData();
    //      Map<String, IStatusProxy> statusProxyMap = mapper.getStatusProxyMap();
    //      List<IVirtualVehicleInfo> virtualVehicleList = mapper.getVirtualVehicleList();

    JSONArray a = new JSONArray();
    for (Entry<String, IRegistrationData> rdEntry : registrationData.entrySet()) {
        IRegistrationData rd = rdEntry.getValue();

        JSONObject o = new JSONObject();
        o.put("regDat", rd);
        a.add(o);
    }

    return JSONValue.toJSONString(a);
}

From source file:com.mapr.xml2json.MySaxParser.java

@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
        throws SAXException {
    super.startElement(uri, localName, qName, attributes);

    JSONObject tag = new JSONObject();
    JSONArray array = new JSONArray();

    int length = attributes.getLength();
    for (int i = 0; i < length; i++) {
        JSONObject temp = new JSONObject();
        String qNameVal = attributes.getQName(i);
        String valueVal = attributes.getValue(i);

        if (qNameVal != null)
            qNameVal = cleanQName(qNameVal);

        if (valueVal.trim().length() > 0) {
            tag.put(qNameVal, valueVal);
            //array.add(temp);
        }/* w  w w . j  ava2 s .co  m*/
    }

    if (array.size() > 0)
        tag.put("attributes", array);
    // tag.put("qName",cleanQName(qName));

    //log.info("After clean:" + cleanQName(qName));
    stk.push(tag);
}

From source file:net.jselby.pc.player.ChatMessage.java

/**
 * Converts a string to a basic ChatMessage
 *
 * @param message The String message//from  ww  w  .jav  a  2 s. co  m
 * @return A Chat message
 */
public static ChatMessage convertToJson(String message) {
    JSONObject obj = new JSONObject();

    // Parse message, looking for colors etc.
    ArrayList<JSONObject> objects = new ArrayList<JSONObject>();

    ChatColor color = ChatColor.WHITE;
    String currentMessage = "";

    boolean nextByteAsColor = false;

    for (char bytes : message.toCharArray()) {
        if (nextByteAsColor) {
            color = ChatColor.getByChar(bytes);
            nextByteAsColor = false;
            continue;
        }
        if (bytes == ChatColor.COLOR_CHAR) { // Special color symbol
            if (currentMessage.length() > 0) {
                JSONObject currentMessageAsJSON = new JSONObject();
                currentMessageAsJSON.put("text", currentMessage);
                currentMessageAsJSON.put("color", color.name().toLowerCase());
                objects.add(currentMessageAsJSON);
            }
            color = ChatColor.WHITE;
            currentMessage = "";
            nextByteAsColor = true;
        } else {
            currentMessage += bytes;
        }
    }

    if (currentMessage.length() > 0) {
        JSONObject rest = new JSONObject();
        rest.put("text", currentMessage);
        rest.put("color", color.name().toLowerCase());
        objects.add(rest);
    }

    JSONArray array = new JSONArray();

    for (JSONObject jsonObject : objects) {
        array.add(jsonObject);
    }

    obj.put("extra", array);
    obj.put("text", "");

    return new ChatMessage(obj);
}