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:Employee.DateGetter.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// w ww.ja 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
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");

    //create and initialize our profile object with passed in parameters
    String ssn = request.getParameter("SSN");
    String profileId = "";
    profileId = request.getParameter("profileId");
    JSONArray jsons = new JSONArray();
    getDates(ssn, jsons, profileId);
    PrintWriter printout = response.getWriter();
    printout.print(jsons);
}

From source file:admin.controller.ServletDisplayLayoutHTML.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w  w w  .j a v  a2  s  .co 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:Javafile.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w w w  .  j  av a2s.  co 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
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/json;charset=UTF-8");

    //System.out.print("I am here");
    try {
        HashMap<String, Integer> words = new HashMap<String, Integer>();
        HashMap<String, String> matchedWords = new HashMap<String, String>();
        readWords(words);
        long totalFind = 0;

        JSONObject wordObj = new JSONObject();
        JSONArray matchedArrayJSON = new JSONArray();
        String s = request.getParameter("inputStr");
        int page = Integer.parseInt(request.getParameter("page"));
        int count;
        count = page * 10;

        totalFind = findMatchedWords(s, words, matchedWords, matchedArrayJSON, count);
        wordObj.put("matchedArrayJSON", matchedArrayJSON);
        wordObj.put("totalFind", totalFind);

        call_Webpage(request, response, wordObj);
    } finally {
    }
}

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

protected static void consultarUsuariosEnConvocatoriaId(HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    ArrayList<UsuarioEntity> usuarios = new ArrayList<>();
    usuarios = CtrlAdmin.obtenerUsuariosEnConvocatoria(Integer.parseInt(request.getParameter("3")), //id evento
            Integer.parseInt(request.getParameter("2")), //tamao tabla
            Integer.parseInt(request.getParameter("1"))//pagina
    );/*  w ww . j av  a2s  .  co m*/

    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);
    }
    out.print(list1);
}

From source file:gov.nih.nci.ispy.web.ajax.IdLookup.java

public String lookup(String ids) {

    String results = "";
    //clean the input and validate
    String inputString = ids.trim().replace(" ", "");
    String[] st = StringUtils.split(inputString, ",");
    //construct the inputlist
    List<String> inputList = new ArrayList<String>();
    inputList = Arrays.asList(st);

    //pass the input list to the service
    List<RegistrantInfo> entries = idMapper.getMapperEntriesForIds(inputList);

    //process the results for return to presentation
    //Document document = DocumentHelper.createDocument();
    //Element container = document.addElement("div");

    JSONArray regs = new JSONArray(); //make an array of registrants
    regs.add(inputString);/*from w  w  w .  j av  a 2 s. c  o m*/

    //Element report = document.addElement( "table" ).addAttribute("name", inputString);
    for (RegistrantInfo entry : entries) {
        //Element reg = report.addElement( "registrant" ).addAttribute("regId", entry.getRegistrationId());

        //for each registrant make an array of samples
        JSONArray sams = new JSONArray();

        for (SampleInfo sampleInfo : entry.getAssociatedSamples()) {

            JSONObject sam = new JSONObject();
            sam.put("regId", entry.getRegistrationId());
            sam.put("labtrackId", sampleInfo.getLabtrackId());
            sam.put("timePoint", String.valueOf(sampleInfo.getTimepoint()));
            sam.put("coreType", String.valueOf(sampleInfo.getCoreType()));
            sam.put("sectionInfo", String.valueOf(sampleInfo.getSectionInfo()));

            /*
            Element row = reg.addElement( "sample" );
                    
            Element cell = row.addElement( "regId" );
                    
            cell.addText(entry.getRegistrationId());
              cell = null;
            cell = row.addElement( "labtrackId" );
            cell.addText(sampleInfo.getLabtrackId());
              cell = null;
            cell = row.addElement( "timePoint" );
            cell.addText(String.valueOf(sampleInfo.getTimepoint()));
              cell = null;
            cell = row.addElement( "coreType" );
            cell.addText(String.valueOf(sampleInfo.getCoreType()));
              cell = null;
            cell = row.addElement( "sectionInfo" );
            cell.addText(String.valueOf(sampleInfo.getSectionInfo()));
                    
            */

            sams.add(sam);
        }

        regs.add(sams);
    }

    /*
    for (RegistrantInfo entry:entries) {
       results += "[\"" + entry.getRegistrationId() + "\"," ;
       for(SampleInfo sampleInfo : entry.getAssociatedSamples())   {
            
       }         
    }
    */

    //return document;
    return regs.toString();

}

From source file:com.megacasting_ppe.web.ServletOffres.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w  w  w  .j av a  2  s.c  om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json;  charset=ISO-8859-1");
    response.setHeader("Cache-Control", "no-cache");

    HttpSession session = request.getSession();

    JSONObject global = new JSONObject();
    JSONArray arrayoffre = new JSONArray();

    //On rcupre le candidat en session 
    Candidat candidat = (Candidat) session.getAttribute("CandidatObject");
    String connecterOk = (String) session.getAttribute("Connecter");

    // si le candidat existe et qu'il est connect
    if (candidat != null && connecterOk != null) {

        JSONObject infoAuth = new JSONObject();

        //je retourne les infomations du candidat connect
        infoAuth.put("Nom", candidat.getNom());
        infoAuth.put("Prenom", candidat.getPrenom());
        infoAuth.put("connecter", connecterOk);

        global.put("infoauth", infoAuth);

    } else {

        JSONObject infoAuth = new JSONObject();
        infoAuth.put("connecter", "false");

        global.put("infoauth", infoAuth);

    }
    ;

    //onrecupre les dix dernires offres en BDD
    for (Offre offre : offreDAO.Lister10()) {

        //On retourne ses offres 
        JSONObject object = new JSONObject();
        object.put("Identifiant", offre.getIdentifiant());
        object.put("Intitule", offre.getLibelle());
        object.put("Reference", offre.getReference());
        object.put("DateDebutContrat", offre.getDateDebutContrat().toString());
        object.put("NombresPoste", offre.getNbPoste());
        object.put("VilleEntreprise", offre.getClient().getVilleEntreprise());

        arrayoffre.add(object);

    }
    global.put("offres", arrayoffre);

    try (PrintWriter out = response.getWriter()) {
        out.println(global.toString());
    }
}

From source file:com.imagelake.android.lightbox.Servlet_LightBox.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    PrintWriter out = response.getWriter();
    String type = request.getParameter("type");
    System.out.println("type :" + type);
    JSONArray box_list = new JSONArray();

    if (type != null) {
        type_id = Integer.parseInt(type);
        if (type_id == LOAD_LIGHTBOX) {

            String userId = request.getParameter("user_id");
            System.out.println("user id :" + userId);
            if (userId != null) {

                user_id = Integer.parseInt(userId);

                Cart c = cdi.getCart(user_id);

                if (c != null) {
                    System.out.println("cart :" + c.getCart_id());
                    List<CartHasImages> list = new CartDAOImp().listUserCartHasImages(c.getCart_id(), 2);
                    if (!list.isEmpty()) {

                        for (CartHasImages ca : list) {

                            im = idi.getImageDetail(ca.getImg_id());
                            //ims=idi.getSubImage(ca.getSubimg_id());

                            if (im.getImage_state_image_state_id() == 1
                                    && im.getImage_state_image_state_id() != 3) {

                                JSONObject jo = new JSONObject();
                                jo.put("cart_id", ca.getCart_has_images_id());
                                jo.put("title", im.getTitle());
                                jo.put("date", ca.getDate());
                                jo.put("state", im.getImage_state_image_state_id());
                                box_list.add(jo);

                            } else if (im.getImage_state_image_state_id() == 5
                                    && im.getImage_state_image_state_id() != 3) {

                                JSONObject jo = new JSONObject();
                                jo.put("cart_id", ca.getCart_has_images_id());
                                jo.put("title", im.getTitle());
                                jo.put("date", ca.getDate());
                                jo.put("state", im.getImage_state_image_state_id());
                                box_list.add(jo);

                            }//from   w w  w . j  ava 2  s  .c  o  m

                        }
                        System.out.println(box_list.toJSONString());
                        out.write("json=" + box_list.toJSONString());
                    } else {
                        out.write("msg=No item found.");
                    }
                } else {

                }

            } else {
                out.write("msg=Internal server error,please try agin later.");
            }
            //List<CartHasImages> list=new CartDAOImp().listUserCartHasImages(c.getCart_id(),1);
        } else if (type_id == LOAD_DATE) {

            String userId = request.getParameter("user_id");

            if (userId != null) {

                user_id = Integer.parseInt(userId);

                Cart c = new CartDAOImp().getCart(user_id);

                if (c != null) {

                    System.out.println("cart :" + c.getCart_id());

                    List<CartHasImages> list = new CartDAOImp().sortByDate(2, "DESC", c.getCart_id(), "date");

                    if (!list.isEmpty()) {

                        for (CartHasImages ca : list) {

                            im = idi.getImageDetail(ca.getImg_id());
                            ims = idi.getSubImage(ca.getSubimg_id());

                            if (im.getImage_state_image_state_id() == 1
                                    && im.getImage_state_image_state_id() != 3) {

                                JSONObject jo = new JSONObject();
                                jo.put("cart_id", ca.getCart_has_images_id());
                                jo.put("title", im.getTitle());
                                jo.put("date", ca.getDate());
                                jo.put("state", im.getImage_state_image_state_id());
                                box_list.add(jo);

                            } else if (im.getImage_state_image_state_id() == 5
                                    && im.getImage_state_image_state_id() != 3) {

                                JSONObject jo = new JSONObject();
                                jo.put("cart_id", ca.getCart_has_images_id());
                                jo.put("title", im.getTitle());
                                jo.put("date", ca.getDate());
                                jo.put("state", im.getImage_state_image_state_id());
                                box_list.add(jo);

                            }
                        }
                        System.out.println(box_list.toJSONString());
                        out.write("json=" + box_list.toJSONString());
                    } else {
                        out.write("msg=No item found.");
                    }
                }

            } else {
                out.write("msg=Internal server error,please try agin later.");
            }

        }

    } else {
        out.write("msg=Internal server error,please try agin later.");
    }
}

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

/**
 * Handle a request for options/*from   w  ww .j a  va  2  s .c  o  m*/
 * @param request the http request
 * @param response the http response
 * @param urn the urn (ignored)
 * @throws MMLException 
 */
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, String urn) throws MMLException {
    try {
        JSONArray annotations = new JSONArray();
        docid = request.getParameter(Params.DOCID);
        version1 = request.getParameter(Params.VERSION1);
        if (docid != null && version1 != null) {
            Connection conn = Connector.getConnection();
            String[] docids = conn.listDocuments(Database.SCRATCH, docid + ".*", JSONKeys.DOCID);
            if (docids != null && docids.length > 0) {
                for (int i = 0; i < docids.length; i++) {
                    JSONObject jObj = fetchAnnotation(conn, Database.SCRATCH, docids[i]);
                    if (jObj != null)
                        annotations.add(jObj);
                }
            }
            if (annotations.isEmpty()) // nothing in SCRATCH space
            {
                docids = conn.listDocuments(Database.ANNOTATIONS, docid + ".*", JSONKeys.DOCID);
                if (docids != null && docids.length > 0) {
                    for (int i = 0; i < docids.length; i++) {
                        JSONObject jObj = fetchAnnotation(conn, Database.ANNOTATIONS, docids[i]);
                        if (jObj != null)
                            annotations.add(jObj);
                    }
                }
            }
        }
        String res = annotations.toJSONString();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().write(res);
    } catch (Exception e) {
        throw new MMLException(e);
    }
}

From source file:identify.SaveToken.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  ww w  .j  a v a 2 s .com*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String acrHeaders = request.getHeader("Access-Control-Request-Headers");
    String acrMethod = request.getHeader("Access-Control-Request-Method");
    String token = request.getParameter("token");
    String username = request.getParameter("username");
    storage.UpdateStorage(token, username);
    JSONObject arrayObj = new JSONObject();
    JSONArray dataArr = new JSONArray();
    arrayObj.put("status", "Ok");
    for (int i = 0; i < storage.getData().size(); i++) {
        JSONObject data = new JSONObject();
        data.put("token", storage.getData().get(i).getToken());
        data.put("username", storage.getData().get(i).getUsername());
        dataArr.add(data);
    }
    if (storage.getData().size() > 9) {
        storage.getData().clear();
    }
    arrayObj.put("storage", dataArr);
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Headers", acrHeaders);
    response.setHeader("Access-Control-Allow-Methods", acrMethod);
    response.setContentType("application/json:charset=UTF-8");
    response.getWriter().write(arrayObj.toString());
}

From source file:modelo.ProcesoVertimientosManagers.ProcesoVertimientos.java

/**
  * //w  w w .ja v a2s . co m
  * Llama al delegate para obtener los clientes.
  * 
  * @param codigoProceso
  * @param nit
  * @param ciiu
  * @param contrato
  * @param razonSocial
  * @param anio
  * @param fechaInicial
  * @param fechaFinal
  * @param filaInicio
  * @param filaFin
  * @return
  * @throws Exception 
  */
public JSONArray getProcesoVertimientos(String codigoProceso, String nit, String contrato, String ciiu,
        String razonSocial, String anio, String fechaInicial, String fechaFinal, String filaInicio,
        String filaFin) throws Exception {

    //Ejecutamos la consulta y obtenemos el ResultSet
    SeleccionarProcesoVertimientos select = new SeleccionarProcesoVertimientos(codigoProceso, nit, contrato,
            ciiu, razonSocial, anio, fechaInicial, fechaFinal, filaInicio, filaFin);
    ResultSet rset = select.ejecutar();

    //Creamos los JSONArray para guardar los objetos JSON
    JSONArray jsonArray = new JSONArray();
    JSONArray jsonArreglo = new JSONArray();
    //Recorremos el ResultSet, armamos el objeto JSON con la info y guardamos

    //en el JSONArray.
    while (rset.next()) {

        //Armamos el objeto JSON con la informacion del registro
        JSONObject jsonObject = new JSONObject();

        jsonObject.put("codigoProceso", rset.getString("CODIGO"));
        jsonObject.put("nit", rset.getString("NIT"));
        jsonObject.put("razonSocial", rset.getString("RAZON_SOCIAL"));
        jsonObject.put("actividadEconomica", rset.getString("CIIU"));
        jsonObject.put("contrato", rset.getString("FK_CONTRATO"));
        jsonObject.put("tipoInforme", rset.getString("TIPOINFORME"));
        jsonObject.put("fechaProceso", rset.getString("FECHA_PROCESO"));
        jsonObject.put("estado", rset.getString("ESTADOP"));
        jsonObject.put("rnum", rset.getString("RNUM"));
        jsonObject.put("valRQ", rset.getString("VALIDAR_RQ"));

        //Guardamos el JSONObject en el JSONArray y lo enviamos a la vista.
        jsonArray.add(jsonObject.clone());

    }

    jsonArreglo.add(jsonArray);

    //Se cierra el ResultSet
    select.desconectar();

    return jsonArreglo;

}