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:modelo.ParametrizacionManagers.TiposInformeVertimientos.java

/**
* SELECT//w ww .jav  a 2  s  .  c  om
* Obtiene la informacion de una unidad de medida y
* guarda todo en un JSONArray para entregarselo a la vista.
* 
* @return JSONArray
* @throws SQLException 
*/

public JSONArray getTiposInformes(String descripcion) throws Exception {

    //Ejecutamos la consulta y obtenemos el ResultSet
    SeleccionarTiposInformesVertimiento seleccionar = new SeleccionarTiposInformesVertimiento();
    ResultSet rst = seleccionar.getTiposInformes(descripcion);

    //Creamos los JSONArray para guardar los objetos JSON
    JSONArray jsonArray = new JSONArray();
    JSONObject jsonObject = new JSONObject();
    JSONArray jsonArreglo = new JSONArray();

    while (rst.next()) {
        //Creamos el objecto JSON
        jsonObject.put("descripcion", rst.getString("DESCRIPCION"));
        jsonObject.put("codigo", rst.getString("CODIGO"));

        //Creamos el Array JSON
        jsonArray.add(jsonObject.clone());

    }

    jsonArreglo.add(jsonArray);
    seleccionar.desconectar();
    return jsonArreglo;

}

From source file:com.aerothai.database.devicetype.DeviceTypeService.java

public JSONObject GetDeviceTypeAt(int id) throws Exception {

    Connection dbConn = null;//  ww  w.  ja  v a2s .c o  m
    JSONObject obj = new JSONObject();
    JSONArray objList = new JSONArray();

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

        Statement stmt = dbConn.createStatement();
        String query = "SELECT * FROM device_type where iddevice_type = " + id;
        System.out.println(query);
        ResultSet rs = stmt.executeQuery(query);

        while (rs.next()) {

            JSONObject jsonData = new JSONObject();
            jsonData.put("id", rs.getInt("iddevice_type"));
            jsonData.put("details", rs.getString("details"));
            jsonData.put("idunit", rs.getString("idunit"));
            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:cpd3314.buildit12.CPD3314BuildIt12.java

/**
 * Build a sample method that saves a handful of car instances as Serialized
 * objects, and as JSON objects./*w  w w. j  a  v a  2s.  c om*/
 */
public static void doBuildIt2Output() {
    Car[] cars = { new Car("Honda", "Civic", 2001), new Car("Buick", "LeSabre", 2003),
            new Car("Toyota", "Camry", 2005) };

    // Saves as Serialized Objects
    try {
        FileOutputStream objFile = new FileOutputStream("cars.obj");
        ObjectOutputStream objStream = new ObjectOutputStream(objFile);

        for (Car car : cars) {
            objStream.writeObject(car);
        }

        objStream.close();
        objFile.close();
    } catch (IOException ex) {
        Logger.getLogger(CPD3314BuildIt12.class.getName()).log(Level.SEVERE, null, ex);
    }

    // Saves as JSONObject
    try {
        PrintWriter jsonStream = new PrintWriter("cars.json");

        JSONArray arr = new JSONArray();
        for (Car car : cars) {
            arr.add(car.toJSON());
        }

        JSONObject json = new JSONObject();
        json.put("cars", arr);

        jsonStream.println(json.toJSONString());

        jsonStream.close();
    } catch (IOException ex) {
        Logger.getLogger(CPD3314BuildIt12.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.owly.srv.BasicDataMetricInJson.java

/**
 * This method will add  a new json array with values the date in epoch mode, and the value capured. This the way flot pluggin in juqery wants the data.
 * @param dateOfValue is the time where the metrics was captures
 * @param Value is the value captured/*from   w  w w . ja va  2  s  .  c  o  m*/
 */
public void addJsonDataArray(Date dateOfValue, float Value) {

    JSONArray jsonArray = new JSONArray();
    jsonArray.add(dateOfValue.getTime());
    jsonArray.add(Value);
    this.jsonDataArray.add(jsonArray);

}

From source file:at.ac.tuwien.dsg.quelle.cloudServicesModel.util.conversions.ConvertToJSON.java

private static JSONObject processMultiLevelRequirementsElement(MultiLevelRequirements multiLevelRequirements) {
    JSONObject rootJSON = new JSONObject();
    rootJSON.put("name", multiLevelRequirements.getName());
    rootJSON.put("level", multiLevelRequirements.getLevel().toString());
    rootJSON.put("type", "RequirementsLevel");

    JSONArray requirementsBlocksArray = new JSONArray();

    for (Requirements r : multiLevelRequirements.getUnitRequirements()) {
        JSONObject requirementsJSON = new JSONObject();
        requirementsJSON.put("name", r.getName());
        requirementsJSON.put("target", r.getTargetServiceID());
        requirementsJSON.put("type", "RequirementsBlock");

        JSONArray requirementsBlockRequirements = new JSONArray();

        for (Requirement requirement : r.getRequirements()) {
            JSONObject requirementJSON = new JSONObject();
            requirementJSON.put("type", "Requirement");
            JSONArray conditionsArray = new JSONArray();

            Metric metric = requirement.getMetric();
            requirementJSON.put("metric", metric.getName() + "[" + metric.getMeasurementUnit() + "]");
            for (Condition condition : requirement.getConditions()) {
                JSONObject conditionJSON = new JSONObject();
                conditionJSON.put("name", condition.toString());
                conditionJSON.put("type", "Condition");
                conditionsArray.add(conditionJSON);
            }//from   ww  w.  j a  va2  s.  c  o  m
            requirementJSON.put("target", r.getTargetServiceID());
            requirementJSON.put("children", conditionsArray);
            requirementsBlockRequirements.add(requirementJSON);
        }
        requirementsJSON.put("children", requirementsBlockRequirements);
        requirementsBlocksArray.add(requirementsJSON);
    }

    rootJSON.put("children", requirementsBlocksArray);

    return rootJSON;
}

From source file:control.ProcesoVertimientosServlets.GenerarExcelVisitas.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from w ww  .  ja va2s. 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 {
    try {

        String fechaInicio = request.getParameter("fechaInicio");
        String fechaFin = request.getParameter("fechaFin");
        String tipoVisita = request.getParameter("tipoVisita");
        String codigoProceso = request.getParameter("codigoProceso");
        String estadoVisita = request.getParameter("estadoVisita");
        String contrato = request.getParameter("contrato");
        String nit = request.getParameter("nit");
        String razonSocial = request.getParameter("razonSocial");
        String motivoVisita = request.getParameter("motivoVisita");

        JSONArray jsonArray = new JSONArray();

        String filaInicio = "";
        String filaFin = "";

        Visitas manager = new Visitas();

        String appDir = getServletContext().getRealPath("/");
        appDir += "sources/Visitas.xls";

        //Llamamos al manager para escribir el excel
        manager.escribirExcel(filaInicio, filaFin, tipoVisita, fechaInicio, fechaFin, codigoProceso, appDir,
                estadoVisita, contrato, nit, razonSocial, motivoVisita);

    } catch (SQLException ex) {
        //Logger.getLogger(GenerarExcelVisitas.class.getName()).log(Level.SEVERE, null, ex);
    }

}

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

private JSONArray login(HttpServletRequest request) throws Exception {
    objArray = new JSONArray();
    if (Conexion.Adminio.equals("si")) {
        LoginHcemed hce = new LoginHcemed();
        Integer idUsuario = hce.login(request.getParameter("usuario"), request.getParameter("contrasena"));
        if (idUsuario > 0) {
            request.getSession().setAttribute("usuario", idUsuario);
            obj = new JSONObject();
            obj.put("Exito", "1");
            objArray.add(obj);/*from   ww  w  . j a  va 2s .c  om*/
        } else {
            obj = new JSONObject();
            obj.put("Error", "datos incorrectos");
            objArray.add(obj);
        }
    } else {
        Usuarios usuario = ejbUsuarios.login(request.getParameter("usuario"),
                request.getParameter("contrasena"));
        if (usuario != null) {
            request.getSession().setAttribute("usuario", usuario.getIdUsuario());
            obj = new JSONObject();
            obj.put("Exito", "1");
            objArray.add(obj);
        } else {
            obj = new JSONObject();
            obj.put("Error", "datos incorrectos");
            objArray.add(obj);
        }
    }
    return objArray;
}

From source file:cloudclient.Client.java

@SuppressWarnings("unchecked")
public static void batchSendTask(PrintWriter out, String workload)
        throws FileNotFoundException, MalformedURLException {

    FileInputStream input = new FileInputStream(workload);
    BufferedReader bin = new BufferedReader(new InputStreamReader(input));

    // Get task from workload file 
    String line;/*from w w  w  .j  a v a  2  s. co  m*/
    //       String sleepLength;
    String id;
    int count = 0;
    final int batchSize = 10;

    try {
        //Get client public IP
        String ip = getIP();
        //System.out.println(ip);

        //JSON object Array      
        JSONArray taskList = new JSONArray();

        while ((line = bin.readLine()) != null) {
            //sleepLength = line.replaceAll("[^0-9]", "");
            //System.out.println(sleepLength);
            count++;
            id = ip + ":" + count;

            JSONObject task = new JSONObject();
            task.put("task_id", id);
            task.put("task", line);

            taskList.add(task);

            if (taskList.size() == batchSize) {
                out.println(taskList.toString());
                taskList.clear();
            }
        }

        //System.out.println(taskList.toString());         
        if (!taskList.isEmpty()) {
            out.println(taskList.toString());
            taskList.clear();
        }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.valygard.aohruthless.utils.inventory.InventoryHandler.java

/**
 * Store the player's inventory in the directory. Doesn't avoid overrides
 * because we are only saving the most recent inventory. This method stores
 * the inventory in memory and on disk for convenience.
 * /*from  w ww.j a  va 2 s. c  o  m*/
 * @param p
 */
@SuppressWarnings("unchecked")
public void storeInventory(Player p) {
    ItemStack[] items = p.getInventory().getContents();
    ItemStack[] armor = p.getInventory().getArmorContents();

    UUID uuid = p.getUniqueId();
    String name = p.getName();

    this.items.put(name, items);
    this.armor.put(name, armor);

    JsonConfiguration json = new JsonConfiguration(dir, uuid.toString());
    json.writeString("last-known-username", name).writeString("uuid", uuid.toString());

    JSONArray contents = new JSONArray();
    JSONArray armorContents = new JSONArray();

    contents.addAll(Arrays.asList(items));
    armorContents.addAll(Arrays.asList(armor));

    json.writeArray("items", contents).writeArray("armor", armorContents);

    contents.clear();
    armorContents.clear();

    // And clear the inventory
    InventoryUtils.clearInventory(p);
}

From source file:co.edu.UNal.ArquitecturaDeSoftware.Bienestar.Vista.App.Admin.CUDEventos.java

protected static void consultarUsuariosEnTallerId(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    ArrayList<UsuarioEntity> usuarios = new ArrayList<>();
    usuarios = CtrlAdmin.obtenerUsuariosEnTaller(Integer.parseInt(request.getParameter("3")),
            Integer.parseInt(request.getParameter("2")), Integer.parseInt(request.getParameter("1")));

    response.setContentType("application/json;charset=UTF-8");
    PrintWriter out = response.getWriter();

    JSONArray list1 = new JSONArray();
    for (UsuarioEntity usuario : usuarios) {
        JSONObject obj = new JSONObject();
        obj.put("id", usuario.getIdUsuario());
        obj.put("titulo", usuario.getNombres() + " " + usuario.getApellidos());
        list1.add(obj);/* w w  w .j a va 2s .c o  m*/
    }
    out.print(list1);
}