Example usage for org.json.simple JSONArray add

List of usage examples for org.json.simple JSONArray add

Introduction

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

Prototype

public boolean add(E e) 

Source Link

Document

Appends the specified element to the end of this list.

Usage

From source file:net.duckling.ddl.web.controller.task.TaskBaseController.java

/**
 * ?JSONJSON? users:[{ id: a ??? value:[{ id:
 * abc@cnic.cn (UID) name: ?? },......] },.... ]
 * //  w w w.  j  ava  2 s .c o m
 * @param list
 * @return
 */
private JSONArray getRegularJSONFromSortedPinyin(List<SimpleUser> list) {
    JSONArray array = new JSONArray();
    if (null != list && !list.isEmpty()) {
        for (SimpleUser su : list) {
            JSONObject temp = new JSONObject();
            temp.put("name", su.getName());
            temp.put("id", su.getUid());
            temp.put("email", su.getEmail());
            array.add(temp);
        }
    }
    return array;
}

From source file:edu.vt.vbi.patric.portlets.TranscriptomicsEnrichment.java

private JSONObject getEnrichmentPathway(ResourceRequest request, List<String> featureIDs) throws IOException {

    DataApiHandler dataApi = new DataApiHandler(request);

    // 1. get Pathway ID, Pathway Name & genomeID
    //solr/pathway/select?q=feature_id:(PATRIC.83332.12.NC_000962.CDS.34.1524.fwd)&fl=pathway_name,pathway_id,gid

    Map<String, JSONObject> pathwayMap = new LinkedHashMap<>();
    Set<String> listFeatureID = new HashSet<>();
    Set<String> listGenomeID = new HashSet<>();
    Set<String> listPathwayID = new HashSet<>();

    SolrQuery query = new SolrQuery("feature_id:(" + StringUtils.join(featureIDs, " OR ") + ")");
    int queryRows = Math.max(dataApi.MAX_ROWS, (featureIDs.size() * 2));
    query.addField("pathway_name,pathway_id,genome_id,feature_id").setRows(queryRows);

    LOGGER.trace("Enrichment 1/3: [{}] {}", SolrCore.PATHWAY.getSolrCoreName(), query);

    String apiResponse = dataApi.solrQuery(SolrCore.PATHWAY, query);

    Map resp = jsonReader.readValue(apiResponse);
    Map respBody = (Map) resp.get("response");
    List<Map> pathwayList = (List) respBody.get("docs");

    for (Map doc : pathwayList) {
        JSONObject pw = new JSONObject();
        pw.put("pathway_id", doc.get("pathway_id"));
        pw.put("pathway_name", doc.get("pathway_name"));
        pathwayMap.put(doc.get("pathway_id").toString(), pw);

        // LOGGER.debug("{}", pw.toJSONString());
        listFeatureID.add(doc.get("feature_id").toString());
        listGenomeID.add(doc.get("genome_id").toString());
        listPathwayID.add(doc.get("pathway_id").toString());
    }/* ww w  .  java2 s  .  com*/

    // 2. get pathway ID & Ocnt
    //solr/pathway/select?q=feature_id:(PATRIC.83332.12.NC_000962.CDS.34.1524.fwd)&rows=0&facet=true
    // &json.facet={stat:{field:{field:pathway_id,limit:-1,facet:{gene_count:"unique(feature_id)"}}}}
    query = new SolrQuery("feature_id:(" + StringUtils.join(featureIDs, " OR ") + ")");
    query.setRows(0).setFacet(true);
    query.add("json.facet",
            "{stat:{field:{field:pathway_id,limit:-1,facet:{gene_count:\"unique(feature_id)\"}}}}");

    LOGGER.trace("Enrichment 2/3: [{}] {}", SolrCore.PATHWAY.getSolrCoreName(),
            URLDecoder.decode(query.toString(), "UTF-8"));

    apiResponse = dataApi.solrQuery(SolrCore.PATHWAY, query);

    resp = jsonReader.readValue(apiResponse);
    Map facets = (Map) resp.get("facets");
    if ((Integer) facets.get("count") > 0) {
        Map stat = (Map) facets.get("stat");
        List<Map> buckets = (List) stat.get("buckets");

        for (Map value : buckets) {
            String aPathwayId = value.get("val").toString();

            if (pathwayMap.containsKey(aPathwayId)) {
                pathwayMap.get(aPathwayId).put("ocnt", value.get("gene_count"));
            }
        }
    }

    // 3. with genomeID, get pathway ID & Ecnt
    //solr/pathway/select?q=genome_id:83332.12 AND pathway_id:(00230 OR 00240)&fq=annotation:PATRIC&rows=0&facet=true //&facet.mincount=1&facet.limit=-1
    // &json.facet={stat:{field:{field:pathway_id,limit:-1,facet:{gene_count:"unique(feature_id)"}}}}
    if (!listGenomeID.isEmpty() && !listPathwayID.isEmpty()) {
        query = new SolrQuery("genome_id:(" + StringUtils.join(listGenomeID, " OR ") + ") AND pathway_id:("
                + StringUtils.join(listPathwayID, " OR ") + ")");
        query.setRows(0).setFacet(true).addFilterQuery("annotation:PATRIC");
        query.add("json.facet",
                "{stat:{field:{field:pathway_id,limit:-1,facet:{gene_count:\"unique(feature_id)\"}}}}");

        LOGGER.trace("Enrichment 3/3: {}", query.toString());

        apiResponse = dataApi.solrQuery(SolrCore.PATHWAY, query);

        resp = jsonReader.readValue(apiResponse);
        facets = (Map) resp.get("facets");
        Map stat = (Map) facets.get("stat");
        List<Map> buckets = (List) stat.get("buckets");

        for (Map value : buckets) {
            pathwayMap.get(value.get("val").toString()).put("ecnt", value.get("gene_count"));
        }
    }

    // 4. Merge hash and calculate percentage on the fly
    JSONObject jsonResult = new JSONObject();
    JSONArray results = new JSONArray();
    for (JSONObject item : pathwayMap.values()) {
        if (item.get("ecnt") != null && item.get("ocnt") != null) {
            float ecnt = Float.parseFloat(item.get("ecnt").toString());
            float ocnt = Float.parseFloat(item.get("ocnt").toString());
            float percentage = ocnt / ecnt * 100;
            item.put("percentage", (int) percentage);
            results.add(item);
        }
    }
    jsonResult.put("results", results);
    jsonResult.put("total", results.size());
    jsonResult.put("featureRequested", featureIDs.size());
    jsonResult.put("featureFound", listFeatureID.size());

    return jsonResult;
}

From source file:name.yumaa.ChromeLogger4J.java

/**
 * Internal logging call/*from  w  w w  . ja va 2 s.c  o  m*/
 * @param type    log type
 * @param args    variables to log
 */
private void _log(String type, Object... args) {
    // nothing passed in, don't do anything
    if (args.length == 0 && !GROUP_END.equals(type))
        return;

    JSONArray log = new JSONArray();
    for (Object arg : args) {
        processed = new ArrayList<Object>();
        try {
            arg = convert(arg, 0);
        } catch (Exception e) {
            arg = e.toString();
        }
        log.add(arg);
    }

    StringBuilder backtrace_message = new StringBuilder(this.stack ? "" : "stack->false");
    if (this.stack) {
        StackTraceElement[] st = Thread.currentThread().getStackTrace();
        for (int i = 0, j = st.length, count = 0; i < j && count < 5; i++) {
            // skip this class calls, native methods and unknown sources
            if (this.className.equals(st[i].getClassName()) || st[i].getFileName() == null
                    || st[i].getLineNumber() < 0)
                continue;

            count++; // count output rows -> print out maximum 5
            backtrace_message.append(st[i].toString());
            if (i + 1 < j && count < 5)
                backtrace_message.append("\n");
        }
    }

    addRow(log, backtrace_message.toString(), type);
    writeHeader(json);
}

From source file:anotadorderelacoes.model.Sentenca.java

/**
 * Retorna a representao em formato JSON desta sentena
 * /* ww w. j  ava 2  s  .  c o  m*/
 * @return String JSON que codifica esta sentena
 */
public String toJson() {

    // ID, texto e comentarios da sentena
    JSONObject json = new JSONObject();
    json.put("id", id);
    json.put("texto", texto);
    json.put("comentarios", comentarios);

    // Tokens
    JSONArray listaTokens = new JSONArray();
    for (Token t : tokens)
        listaTokens.add(t.toJson());
    json.put("tokens", listaTokens);

    // Termos
    JSONArray listaTermos = new JSONArray();
    for (Termo t : termos)
        listaTermos.add(t.toJson());
    json.put("termos", listaTermos);

    // Relaoes
    JSONArray listaRelacoes = new JSONArray();
    for (Relacao r : relacoes) {
        JSONObject o = new JSONObject();
        o.put("r", r.getRelacao());
        o.put("t1", termos.indexOf(r.getTermo1()));
        o.put("t2", termos.indexOf(r.getTermo2()));
        listaRelacoes.add(o);
    }
    json.put("relacoes", listaRelacoes);

    // Anotadores
    JSONArray listaAnotadores = new JSONArray();
    for (String a : anotadores)
        listaAnotadores.add(a);
    json.put("anotadores", listaAnotadores);

    json.put("anotada", anotada);
    json.put("ignorada", ignorada);

    return json.toString();

}

From source file:api.conferences.ConferenceList.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   ww w. j av a2s . 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 {
    // request { categoryId: 1 , categoryName: "" , timeStart: "",  timeEnd: "",  location: [] }
    String categoryId = request.getParameter("categoryId");
    String categoryName = request.getParameter("categoryName");

    String timeStart = request.getParameter("timeStart");
    String timeEnd = request.getParameter("timeEnd");

    String locations = request.getParameter("locations");

    if (categoryId != null) {
        Integer.parseInt(categoryId);
    }

    if (locations != null) {
        locations = locations.substring(1, locations.length() - 1);
    }

    List<Map<String, Object>> allResults = this.getAllConferences();
    JSONObject conferences = new JSONObject();
    JSONArray conferenceList = new JSONArray();
    for (Map<String, Object> result : allResults) {
        Iterator it = result.entrySet().iterator();
        JSONObject conference = new JSONObject();
        while (it.hasNext()) {
            Map.Entry pair = (Map.Entry) it.next();
            Object value = pair.getValue();
            System.out.println(pair.getKey() + " = " + value);
            if (value instanceof Timestamp) {
                value = value.toString();
            }
            conference.put(pair.getKey(), value);

            it.remove(); // avoids a ConcurrentModificationException
        }
        conferenceList.add(conference);
    }

    conferences.put("conferences", conferenceList);

    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        out.write(conferences.toJSONString());

        out.close();
    }

}

From source file:modelo.ProcesoVertimientosManagers.VerificacionInfoCaracterizacion.java

public JSONArray getVerificacionInfoCaracterizacion(Integer codigoProceso, Integer tipoInforme)
        throws SQLException {

    ResultSet rset = null;/*from  www.j  a  v a  2 s .  com*/
    JSONArray jsonArray = new JSONArray();
    JSONObject jsonObject = new JSONObject();
    JSONArray jsonArrayPreguntas = new JSONArray();

    //Se crea el objeto
    SeleccionarVerificacionInfoCaracterizacion select = new SeleccionarVerificacionInfoCaracterizacion(
            codigoProceso, tipoInforme);

    //Seleccionamos los "Hijos" y  "Nietos" del requisito "Padre"
    rset = select.getVerificaciones();

    while (rset.next()) {

        jsonObject.put("codigo", rset.getString("CODIGO"));
        jsonObject.put("reguisito", rset.getString("DESCRIPCION"));
        jsonObject.put("fk_informe", rset.getString("FK_TIPO_INFORME"));
        jsonObject.put("checkeado", rset.getString("TIENE"));

        jsonArray.add(jsonObject.clone());

    }

    jsonArrayPreguntas.add(jsonArray.clone());

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

    return jsonArrayPreguntas;
}

From source file:admin.controller.ServletDisplayLayoutHTML.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w  w  w . ja  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
 */
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:jp.aegif.nemaki.rest.UserResource.java

@SuppressWarnings("unchecked")
@GET/*from w ww  .ja v  a2 s.com*/
@Path("/list")
@Produces(MediaType.APPLICATION_JSON)
public String list(@PathParam("repositoryId") String repositoryId) {
    boolean status = true;
    JSONObject result = new JSONObject();
    JSONArray listJSON = new JSONArray();
    JSONArray errMsg = new JSONArray();

    // Get all users list
    List<User> userList;
    try {
        userList = principalService.getUsers(repositoryId);
        for (User user : userList) {
            JSONObject userJSON = convertUserToJson(user);
            listJSON.add(userJSON);
        }
        result.put("users", listJSON);
    } catch (Exception e) {
        status = false;
        e.printStackTrace();
        addErrMsg(errMsg, ITEM_ALLUSERS, ErrorCode.ERR_LIST);
    }
    result = makeResult(status, result, errMsg);
    return result.toJSONString();
}

From source file:com.imagelake.control.CreditsDAOImp.java

public String getFullSliceDetails() {
    String sb = "";
    JSONArray ja = new JSONArray();
    try {// w ww. j a  v  a  2  s.c om

        String sql2 = "SELECT * FROM credits WHERE state='1'";
        PreparedStatement ps2 = DBFactory.getConnection().prepareStatement(sql2);
        ResultSet rs2 = ps2.executeQuery();

        while (rs2.next()) {
            JSONObject jo = new JSONObject();
            jo.put("id", rs2.getInt(1));
            jo.put("credits", rs2.getInt(2));
            jo.put("size", rs2.getString(3));
            jo.put("width", rs2.getInt(4));
            jo.put("height", rs2.getInt(5));
            ja.add(jo);
        }
        sb = "json=" + ja.toJSONString();

    } catch (Exception e) {
        e.printStackTrace();
        sb = "msg=Internal server error,Please try again later.";
    }
    return sb;
}

From source file:edu.vt.vbi.patric.portlets.CompPathwayTable.java

@SuppressWarnings("unchecked")
private void getFilterData(ResourceRequest request, ResourceResponse response)
        throws PortletException, IOException {
    JSONObject val = new JSONObject();
    try {/*from www . java2  s. com*/
        if (request.getParameter("val") != null) {
            LOGGER.trace("parsing param: {}", request.getParameter("val"));
            val = (JSONObject) (new JSONParser()).parse(request.getParameter("val"));
        }
    } catch (ParseException e) {
        LOGGER.error(e.getMessage(), e);
    }

    DataApiHandler dataApi = new DataApiHandler(request);
    JSONObject json = new JSONObject();

    String need = val.get("need") != null ? val.get("need").toString() : "";

    JSONObject defaultItem = new JSONObject();
    defaultItem.put("name", "ALL");
    defaultItem.put("value", "ALL");

    JSONArray items = new JSONArray();
    items.add(defaultItem);

    switch (need) {
    case "pathway":
        try {
            Map facets = dataApi.getPivotFacets(SolrCore.PATHWAY_REF, "*:*", null, "pathway_id,pathway_name");

            Map pivot = (Map) facets.get("pathway_id,pathway_name");

            for (Map.Entry entry : (Iterable<Map.Entry>) pivot.entrySet()) {

                Map entryValue = (Map) entry.getValue();
                String key = (String) entryValue.keySet().iterator().next();

                JSONObject item = new JSONObject();
                item.put("name", key);
                item.put("value", entry.getKey());

                items.add(item);
            }

            json.put(need, items);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }

        break;
    case "ec":
        try {
            Map facets = dataApi.getFieldFacets(SolrCore.PATHWAY_REF, "*:*", null, "ec_number");
            Map list = (Map) ((Map) facets.get("facets")).get("ec_number");

            for (Map.Entry entry : (Iterable<Map.Entry>) list.entrySet()) {
                JSONObject i = new JSONObject();
                i.put("name", entry.getKey());
                i.put("value", entry.getKey());

                items.add(i);
            }

            json.put(need, items);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }

        break;
    case "parent":
        try {
            Map facets = dataApi.getFieldFacets(SolrCore.PATHWAY_REF, "*:*", null, "pathway_class");
            Map list = (Map) ((Map) facets.get("facets")).get("pathway_class");

            for (Map.Entry entry : (Iterable<Map.Entry>) list.entrySet()) {
                JSONObject i = new JSONObject();
                i.put("name", entry.getKey());
                i.put("value", entry.getKey());

                items.add(i);
            }

            json.put(need, items);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
        break;
    case "algorithm":
        JSONObject annotationPATRIC = new JSONObject();
        annotationPATRIC.put("name", "PATRIC");
        annotationPATRIC.put("value", "PATRIC");
        items.add(annotationPATRIC);

        json.put(need, items);
        break;
    }
    response.setContentType("application/json");
    json.writeJSONString(response.getWriter());
}