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:com.johncroth.histo.logging.LogHistogramWriter.java

@SuppressWarnings("unchecked")
JSONObject convert(LogHistogramRecorder rec) {
    JSONObject jo = new JSONObject();
    for (String key : rec.getHistogramMap().keySet()) {
        jo.put(key, convert(rec.getHistogramMap().get(key)));
    }// w w  w .  ja  v  a  2  s.c  o  m
    return jo;
}

From source file:control.UsuariosServlets.InsertarUsuario.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from   w  ww. ja  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
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Integer respuesta = 0;

    try {
        String usuario = request.getParameter("descripcion");
        Integer rol = Integer.parseInt(request.getParameter("rol"));

        Usuarios manager = new Usuarios();
        respuesta = manager.insertarUsuarios(usuario, rol);

        //Armamos la respuesta JSON y la enviamos
        response.setContentType("application/json");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("error", respuesta);
        response.getWriter().write(jsonObject.toString());

    } catch (Exception ex) {

        //Armamos la respuesta JSON y la enviamos
        response.setContentType("application/json");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("error", respuesta);
        response.getWriter().write(jsonObject.toString());
    }

}

From source file:model.Summary.java

public JSONObject toJSON() {
    JSONObject json = new JSONObject();
    json.put("city", city);
    json.put("health", health);
    json.put("stress", stress);
    json.put("expenses", expenses);
    json.put("historicalExpenses", historicalExpenses);
    return json;//  w w w. j  a v  a 2 s  .  com
}

From source file:manager.GameElement.java

public static JSONObject toJSON() {
    JSONObject json = new JSONObject();

    json.put("level", String.valueOf(level));
    json.put("experience", String.valueOf(experience));
    json.put("streak", String.valueOf(streak));

    return json;/*from  w ww .j a  v a  2s .c o m*/
}

From source file:mongodbutils.Filehandler.java

public boolean processFile(String filePath, MongodbConnection mc, String strdbName, String strCollName)
        throws IOException {
    this.mc = mc;

    FileInputStream fileIn = null;
    try {//from  w  w w .j a  v  a  2  s.c o m
        fileIn = new FileInputStream(filePath);
        POIFSFileSystem fs = new POIFSFileSystem(fileIn);
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        HSSFSheet sheet = wb.getSheetAt(0);

        Object objReturn = null;

        //Read in first row as field names
        Row rowH = sheet.getRow(sheet.getFirstRowNum());
        String fields[] = new String[sheet.getRow(0).getLastCellNum()];
        for (Cell cell : rowH) {
            objReturn = null;
            objReturn = getCellValue(cell);
            fields[cell.getColumnIndex()] = objReturn.toString();
        }

        //loop thru all cells with values
        int rowcount = 0;
        for (Row row : sheet) {
            if (row.getRowNum() == 0) {
                continue; //skip first row
            }
            JSONObject obj = new JSONObject();

            for (Cell cell : row) {
                if (fields.length < cell.getColumnIndex()) {
                    continue; //only export column if we have header set
                }
                objReturn = null;
                objReturn = getCellValue(cell);
                if (!objReturn.toString().equals("")) {
                    if (objReturn instanceof Double) {
                        obj.put(fields[cell.getColumnIndex()], objReturn);

                    } else if (objReturn instanceof String) {
                        if (objReturn.toString().contains("$date")) {
                            JSONParser parser = new JSONParser();
                            try {
                                obj.put(fields[cell.getColumnIndex()], parser.parse(objReturn.toString()));
                            } catch (ParseException ex) {
                                Logger.getLogger(Filehandler.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        } else {
                            obj.put(fields[cell.getColumnIndex()], objReturn);
                        }
                    }
                }
            }
            rowcount += 1;
            mc.insertJSON(strdbName, strCollName, obj.toJSONString());
        }

        return true;
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Filehandler.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Filehandler.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception e) {
        Logger.getLogger(Filehandler.class.getName()).log(Level.SEVERE, null, e);
    } finally {
        if (fileIn != null) {
            fileIn.close();
        }
    }
    return false;
}

From source file:com.appzone.sim.services.handlers.ReceiveSmsCheckServiceHandler.java

@Override
protected String doProcess(HttpServletRequest request) {

    String address = request.getParameter(KEY_ADDRESS);
    String sinceStr = request.getParameter(KEY_SINCE);
    logger.debug("request sms messages for: {} since: {}", address, sinceStr);
    long since = Long.parseLong(sinceStr);

    List<Sms> messages = smsRepository.find(address, since);

    JSONArray list = new JSONArray();

    for (Sms sms : messages) {
        JSONObject json = new JSONObject();
        json.put(JSON_KEY_MESSAGE, sms.getMessage());
        json.put(JSON_KEY_RECEIVED_DATE, sms.getReceivedDate());

        list.add(json);/*w ww. j av  a2  s  .c om*/
    }

    logger.debug("returning response: {}", list);

    return list.toJSONString();
}

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 "";
    }/* w w w . j a  v  a2  s .c om*/

    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:bookUtilities.AddBookServlet.java

private JSONObject addBook(String title, String cover, String author, String genre, String description,
        String language, String publisher, String fileURL) {

    JSONObject messageToReturn = new JSONObject();
    try {/*from   w ww.  ja  v  a 2  s . com*/
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

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

        Statement st = con.createStatement();
        Calendar someDate = Calendar.getInstance();
        someDate.setTime(new Date());
        Timestamp stamp = new Timestamp(someDate.getTimeInMillis());
        String query = "DECLARE @newId UNIQUEIDENTIFIER; " + "SET @newid = NEWID(); "
                + "INSERT INTO [HardCover].[dbo].[Book] " + "VALUES (@newid, '" + title + "', '" + cover
                + "', '" + stamp + "', 5, 0, '" + language + "', '" + description + "', '" + publisher
                + "', 1); ";
        String[] authors = author.split(", ");
        String[] genres = genre.split(", ");
        String[] files = fileURL.split(", ");
        for (String s : authors) {
            query += "INSERT INTO [HardCover].[dbo].[Author] (AuthorName, BookId)" + "VALUES('" + s
                    + "', @newid); ";
        }
        for (String s : genres) {
            query += "INSERT INTO [HardCover].[dbo].[Genre] (Genre, BookId)" + "VALUES('" + s + "', @newid); ";
        }
        for (String s : files) {
            query += "INSERT INTO [HardCover].[dbo].[BookFileType] (FileType, DownloadLink, BookId)"
                    + "VALUES('pdf', '" + s + "', @newid); ";
        }
        st.executeUpdate(query);
        messageToReturn.put("message", "success");
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    return messageToReturn;
}

From source file:modelo.ParametrizacionManagers.Laboratorios.java

/**
* 
* Llama al delegate para Eliminar un Laboratorio
* 
* @param codigo     //from   w  w w . j ava  2s . c  o m
* @throws Exception 
*/
public JSONArray Eliminar(int codigo) throws Exception {

    JSONArray jsonArray = new JSONArray();
    JSONObject jsonObject = new JSONObject();

    Integer respError;

    EliminarLaboratorios delete = new EliminarLaboratorios(codigo);
    delete.ejecutar();

    respError = delete.getError();

    jsonObject.put("error", respError);

    jsonArray.add(jsonObject);

    return jsonArray;

}

From source file:modelo.ParametrizacionManagers.DocumentacionRequerida.java

/**
* 
* Llama al delegate para Eliminar una unidad de medida.
* 
* @param codigo     //from w w w  .  j  a v  a2 s.co m
* @throws Exception 
*/
public JSONArray eliminar(int codigo) throws Exception {

    JSONArray jsonArray = new JSONArray();
    JSONObject jsonObject = new JSONObject();

    Integer respError;

    EliminarDocumentacionRequerida delete = new EliminarDocumentacionRequerida(codigo);
    delete.ejecutar();

    respError = delete.getError();

    jsonObject.put("error", respError);

    jsonArray.add(jsonObject);

    return jsonArray;

}