Example usage for org.json.simple JSONObject JSONObject

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

Introduction

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

Prototype

JSONObject

Source Link

Usage

From source file:formatter.handler.post.FormatterPostHandler.java

public FormatterPostHandler() {
    this.userdata = new JSONObject();
    // use empty guest account
    this.userdata.put(JSONKeys.NAME, "guest");
    this.userdata.put(JSONKeys.ROLES, new JSONArray());
}

From source file:de.hstsoft.sdeep.model.Note.java

@SuppressWarnings("unchecked")
public JSONObject toJson() {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("x", (float) position.getX());
    jsonObject.put("y", (float) position.getY());
    jsonObject.put("title", title);
    jsonObject.put("text", text);
    jsonObject.put("year", year);
    jsonObject.put("month", month);
    jsonObject.put("day", day);
    jsonObject.put("daysSurvived", daysSurvived);

    return jsonObject;
}

From source file:com.oic.utils.TestValiadtion.java

public void testMaxLength() {
    JSONObject json = new JSONObject();
    json.put("name", "aaa");
    Validators v = new Validators(json);
    v.add("name", v.maxLength(3));
    assertTrue(v.validate());/*from  ww w.  j a va 2  s.c  om*/
    json.put("name", "aaaa");
    v = new Validators(json);
    v.add("name", v.maxLength(3));
    assertFalse(v.validate());
}

From source file:com.johncroth.histo.logging.LogHistogramWriter.java

@SuppressWarnings("unchecked")
JSONObject convert(LogHistogram x) {/* www.ja va 2s  . c  om*/
    JSONObject jo = new JSONObject();
    for (Map.Entry<Integer, Bucket> entry : x.getBucketMap().entrySet()) {
        JSONObject b = new JSONObject();
        b.put(COUNT, entry.getValue().getCount());
        b.put(WEIGHT, entry.getValue().getWeight());
        jo.put(entry.getKey(), b);
    }
    return jo;
}

From source file:ch.zhaw.icclab.tnova.expressionsolver.OTFlyEval.java

@POST
@Consumes(MediaType.APPLICATION_JSON)//from  w ww. jav a 2 s.c o  m
@Produces(MediaType.APPLICATION_JSON)
public Response evalOnTheFly(String incomingMsg) {
    JSONObject incoming = (JSONObject) JSONValue.parse(incomingMsg);
    JSONObject outgoing = new JSONObject();
    String result = "";
    try {
        String expression = (String) incoming.get("exp");
        JSONArray vals = (JSONArray) incoming.get("values");
        Stack<Double> param = new Stack<Double>();
        for (int i = 0; i < vals.size(); i++) {
            Double val = new Double((String) vals.get(i));
            param.push(val);
        }
        double threshold = Double.parseDouble((String) incoming.get("threshold"));
        result = evaluateExpression(expression, param, threshold);
    } catch (Exception ex) {
        if (App.showExceptions)
            ex.printStackTrace();
    }
    logger.info("received expression: " + incoming.get("exp"));
    logger.info("expression evaluation result: " + result);
    //construct proper JSON response.
    outgoing.put("info", "t-nova expression evaluation service");
    if (result != null && result.length() != 0) {
        outgoing.put("result", result);
        outgoing.put("status", "ok");
        KPI.expressions_evaluated += 1;
        KPI.api_calls_success += 1;
        return Response.ok(outgoing.toJSONString(), MediaType.APPLICATION_JSON_TYPE).build();
    } else {
        outgoing.put("status", "execution failed");
        outgoing.put("msg",
                "malformed request parameters, check your expression or parameter list for correctness.");
        KPI.expressions_evaluated += 1;
        KPI.api_calls_failed += 1;
        return Response.status(Response.Status.BAD_REQUEST).entity(outgoing.toJSONString())
                .encoding(MediaType.APPLICATION_JSON).build();
    }
}

From source file:admin.controller.ServletDisplayLayoutHTML.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//ww  w .  j  a va 2  s  .c o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);

    response.setContentType("application/json");
    String modelname = request.getParameter("modelname");

    try (PrintWriter out = response.getWriter()) {
        JSONArray json_arr = new JSONArray();
        JSONObject json_ob = new JSONObject();
        File divFile = new File(AppConstants.LAYOUT_HTML_HOME + File.separator + modelname + ".html");
        String layoutHTMLDiv = "";

        if (divFile.exists())
            layoutHTMLDiv = FileUtils.readFileToString(divFile, "UTF-8");
        json_ob.put("div", layoutHTMLDiv);
        String layoutHTMLTable = "";
        File tableFile = new File(
                AppConstants.BASE_HTML_TEMPLATE_UPLOAD_PATH + File.separator + modelname + ".html");
        if (tableFile.exists())
            layoutHTMLTable = FileUtils.readFileToString(tableFile, "UTF-8");
        json_ob.put("table", layoutHTMLTable);

        json_arr.add(json_ob);
        out.write(new Gson().toJson(json_arr));
    } catch (Exception e) {
        logger.log(Level.SEVERE, util.Utility.logMessage(e, "Exception:", e.getMessage()));

    }
}

From source file:bookUtilities.BookInfoServlet.java

private JSONObject getBookInfo(String bookId) {
    JSONObject ourBook = new JSONObject();
    try {//from  ww w  .j  a v  a 2 s.  c om
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

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

        Statement st = con.createStatement();
        Statement st2 = con.createStatement();
        Statement st3 = con.createStatement();
        String query = "SELECT * " + "FROM [HardCover].[dbo].[Book] " + "WHERE BookUuid = '" + bookId
                + "' AND Active = 1;";

        String query2 = "SELECT AuthorName " + "FROM [HardCover].[dbo].[Author] " + "WHERE BookId = '" + bookId
                + "';";

        String query3 = "SELECT Genre " + "FROM [HardCover].[dbo].[Genre] " + "WHERE BookId = '" + bookId
                + "';";

        ResultSet rs = st.executeQuery(query);
        ResultSet rs2 = st2.executeQuery(query2);
        ResultSet rs3 = st3.executeQuery(query3);

        rs.next();
        String authors = "";
        while (rs2.next()) {
            if (authors.isEmpty()) {
                authors = rs2.getString("AuthorName");
            } else {
                authors = authors + ", " + rs2.getString("AuthorName");
            }
        }
        String genres = "";
        while (rs3.next()) {
            if (genres.isEmpty()) {
                genres = rs3.getString("Genre");
            } else {
                genres = genres + ", " + rs3.getString("Genre");
            }
        }
        ourBook.put("authors", authors);
        ourBook.put("genres", genres);
        ourBook.put("title", rs.getString("Title"));
        ourBook.put("description", rs.getString("BookDescription"));
        ourBook.put("cover", rs.getString("Cover"));
        ourBook.put("numCopies", rs.getString("NumCopies"));
        ourBook.put("language", rs.getString("BookLanguage"));
        ourBook.put("publisher", rs.getString("Publisher"));
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

    return ourBook;
}

From source file:bookUtilities.RemoveBookServlet.java

private JSONObject removeBook(String bookId) {
    JSONObject messageToReturn = new JSONObject();

    try {//from  ww  w.jav  a2s  . com
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

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

        Statement st = con.createStatement();

        String query = "UPDATE HardCover.dbo.Book " + "SET Active = 0 " + "WHERE BookUuid = '" + bookId + "';";

        st.executeUpdate(query);
        messageToReturn.put("message", "success");
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    return messageToReturn;

}

From source file:com.opensoc.parsing.parsers.BasicSourcefireParser.java

@SuppressWarnings({ "unchecked", "unused" })
public JSONObject parse(byte[] msg) {

    JSONObject payload = new JSONObject();
    String toParse = "";

    try {//  www.j  av a2 s  .com

        toParse = new String(msg, "UTF-8");
        _LOG.debug("Received message: " + toParse);

        String tmp = toParse.substring(toParse.lastIndexOf("{"));
        payload.put("key", tmp);

        String protocol = tmp.substring(tmp.indexOf("{") + 1, tmp.indexOf("}")).toLowerCase();
        String source = tmp.substring(tmp.indexOf("}") + 1, tmp.indexOf("->")).trim();
        String dest = tmp.substring(tmp.indexOf("->") + 2, tmp.length()).trim();

        payload.put("protocol", protocol);

        String source_ip = "";
        String dest_ip = "";

        if (source.contains(":")) {
            String parts[] = source.split(":");
            payload.put("ip_src_addr", parts[0]);
            payload.put("ip_src_port", parts[1]);
            source_ip = parts[0];
        } else {
            payload.put("ip_src_addr", source);
            source_ip = source;

        }

        if (dest.contains(":")) {
            String parts[] = dest.split(":");
            payload.put("ip_dst_addr", parts[0]);
            payload.put("ip_dst_port", parts[1]);
            dest_ip = parts[0];
        } else {
            payload.put("ip_dst_addr", dest);
            dest_ip = dest;
        }

        payload.put("timestamp", System.currentTimeMillis());

        Matcher sidMatcher = sidPattern.matcher(toParse);
        String originalString = null;
        String signatureId = "";
        if (sidMatcher.find()) {
            signatureId = sidMatcher.group(2);
            originalString = sidMatcher.group(1) + " " + sidMatcher.group(2) + " " + sidMatcher.group(3);
        } else {
            _LOG.warn("Unable to find SID in message: " + toParse);
            originalString = toParse;
        }
        payload.put("original_string", originalString);
        payload.put("signature_id", signatureId);

        return payload;
    } catch (Exception e) {
        e.printStackTrace();
        _LOG.error("Failed to parse: " + toParse);
        return null;
    }
}

From source file:control.ProcesoVertimientosServlets.EliminarAnexosMonitoreo.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from   w w w. j ava  2  s  .  co  m
 * @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 resp = new JSONObject();
    try {
        Integer codigoArchivo = Integer.parseInt(request.getParameter("codigoArchivo"));
        Integer codigoMonitoreo = Integer.parseInt(request.getParameter("codigoMonitoreo"));

        ProgramarMonitoreo manager = new ProgramarMonitoreo();

        resp = manager.eliminarAnexos(codigoArchivo, codigoMonitoreo);

        response.setContentType("application/json");
        response.getWriter().write(resp.toString());

    } catch (Exception ex) {
        resp.put("error", 0);
        response.getWriter().write(resp.toString());
    }

}