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:analysers.ExportValidated.java

/**
 * Make JSON Object for a lineage/*from   ww  w  .j  ava  2 s  . c  o m*/
 * @param a the ancestral cell of the lineage
 * @param nlin the lineage number
 * @return
 */
@SuppressWarnings("unchecked")
private JSONObject makeLineageJSON(Cell a, int nlin) {
    double dt = exp.getFrameInterval();
    JSONArray cs = new JSONArray();
    JSONObject l = new JSONObject();

    l.put("dt", dt);
    // also remember the intensity value type
    l.put("mean_intensities", Prefs.getInt(".TrackApp.FilterValidatedDialog.exportMean", 1));

    ArrayList<Cell> cells = new ArrayList<Cell>();
    HashMap<Integer, String> cellNames = new HashMap<Integer, String>();
    JSONArray divns = new JSONArray();
    cells.add(a);
    getAllDaughters(a, cells, cellNames, null, divns);

    l.put("divisions", divns);

    int cellid = 1;
    HashMap<String, Integer> cellsToCellsInLin = new HashMap<String, Integer>();

    int minframe = -1;
    int maxframe = -1;

    for (Iterator<Cell> i = cells.iterator(); i.hasNext();) {
        Cell cell = (Cell) i.next();

        if (minframe < 0 || cell.getFrame() < minframe) {
            minframe = cell.getFrame();
        }
        int clf = findLastFrame(cell);
        if (maxframe < 0 || clf > maxframe) {
            maxframe = clf;
        }

        cellsToCellsInLin.put("" + cell.getCellID(), new Integer(cellid));
        ++cellid;
    }

    // make lineage time axis (minframe -> maxframe)
    JSONArray lintime = new JSONArray();
    for (int f = minframe; f <= maxframe; ++f) {
        lintime.add(new Double((f - 1) * dt));
    }
    l.put("time", lintime);

    cellid = 1;
    for (Iterator<Cell> i = cells.iterator(); i.hasNext();) {
        Cell cell = (Cell) i.next();
        JSONObject co = makeCellJSON(cell);
        co.put("lineage", new Integer(nlin));

        int parent = 0;
        // parent is first cell back for which we have an id, or 0
        Cell pcell = cell.getPreviousCell();
        Cell ppcell = pcell;
        int f = 0;
        while (pcell != null) {
            int id = pcell.getCellID();
            Integer pi = cellsToCellsInLin.get("" + id);
            if (pi != null) {
                parent = pi.intValue();
                break;
            }
            ppcell = pcell;
            pcell = pcell.getPreviousCell();
            if (f++ > maxframe) {
                IJ.log("Failed to find parent for cell " + cell.getCellID());
                break;
            }
        }
        if (cellid != 1 && parent == 0) {
            IJ.log("Error: parent is null within lineage!" + ppcell.toString());
        }

        co.put("parent", new Integer(parent));
        co.put("parent_in_lineage", new Integer(parent));

        co.put("lineage_id", new Integer(cellid));
        co.put("name", cellNames.get(cell.getCellID()));

        cs.add(co);
        ++cellid;
    }

    JSONObject o = new JSONObject();
    o.put("lin", l);
    o.put("cells", cs);

    return o;
}

From source file:jp.aegif.nemaki.rest.UserResource.java

/**
 * Search user by id TODO Use Solr//from w w  w.  j a v a 2  s  .  c  om
 *
 * @param query
 * @return
 */
@SuppressWarnings("unchecked")
@GET
@Path("/search")
@Produces(MediaType.APPLICATION_JSON)
public String search(@PathParam("repositoryId") String repositoryId, @QueryParam("query") String query) {
    boolean status = true;
    JSONObject result = new JSONObject();
    JSONArray errMsg = new JSONArray();

    List<User> users;
    JSONArray queriedUsers = new JSONArray();
    users = principalService.getUsers(repositoryId);
    for (User user : users) {
        if (user.getUserId().startsWith(query) || user.getName().startsWith(query)) {
            JSONObject userJSON = convertUserToJson(user);
            queriedUsers.add(userJSON);
        }
    }

    if (queriedUsers.isEmpty()) {
        status = false;
        addErrMsg(errMsg, ITEM_USER, ErrorCode.ERR_NOTFOUND);
    } else {
        result.put("result", queriedUsers);
    }

    result = makeResult(status, result, errMsg);
    return result.toJSONString();
}

From source file:gwap.rest.User.java

private JSONObject getUserStatistics(String deviceId, Person person) {
    Query query;//from w w  w.  j ava 2s. c  o m
    String username = person.getExternalUsername();

    query = entityManager.createNamedQuery("gameRound.statisticsByPlayer");
    query.setParameter("deviceId", deviceId);
    UserStatistics userStatistics = (UserStatistics) query.getSingleResult();

    query = entityManager.createNamedQuery("gameRound.gamesWonByPlayer");
    query.setParameter("deviceId", deviceId);
    Long gamesWonByPlayer = ((Number) query.getSingleResult()).longValue();

    query = entityManager.createNamedQuery("artResource.byOriginAndDeviceId");
    query.setParameter("origin", ArtResource.ORIGIN_APP_USER);
    query.setParameter("deviceId", deviceId);
    Long photosTaken = ((Number) query.getSingleResult()).longValue();

    query = entityManager.createNamedQuery("artResource.byOriginAndDeviceId");
    query.setParameter("origin", ArtResource.ORIGIN_APP_CRIMESCENE);
    query.setParameter("deviceId", deviceId);
    Long crimescenesTaken = ((Number) query.getSingleResult()).longValue();

    query = entityManager.createNamedQuery("badge.byDeviceId");
    query.setParameter("deviceId", deviceId);
    List<Badge> unlockedBadges = query.getResultList();

    query = entityManager.createNamedQuery("badge.byPlatform");
    query.setParameter("platform", "inspectorXApp");
    List<Badge> allBadges = query.getResultList();

    query = entityManager.createNamedQuery("highscore.all");
    query.setParameter("gametype", getGameType());
    List<Highscore> highscores = query.getResultList();
    int highscoreRank = 0;
    for (int i = 0; i < highscores.size(); i++) {
        if (highscores.get(i).getPersonId().equals(person.getId())) {
            highscoreRank = i + 1;
            break;
        }
    }

    JSONObject userObject = new JSONObject();
    userObject.put("id", deviceId);
    userObject.put("username", username);
    userObject.put("score", userStatistics.getScore());
    userObject.put("playedTime", userStatistics.getSecondsPlayed());
    userObject.put("gamesPlayed", gamesWonByPlayer);
    userObject.put("photosTaken", photosTaken);
    userObject.put("crimescenesTaken", crimescenesTaken);
    userObject.put("coveredDistance", userStatistics.getCoveredDistance());
    userObject.put("rank", highscoreRank);

    JSONArray badgesArray = new JSONArray();
    for (Badge badge : allBadges) {
        JSONObject jsonBadge = new JSONObject();
        jsonBadge.put("id", badge.getId());
        jsonBadge.put("name", badge.getName());
        jsonBadge.put("description", badge.getDescription());
        jsonBadge.put("worth", badge.getWorth());
        if (unlockedBadges.contains(badge))
            jsonBadge.put("unlocked", true);
        else
            jsonBadge.put("unlocked", false);
        badgesArray.add(jsonBadge);
    }
    userObject.put("badges", badgesArray);
    return userObject;
}

From source file:com.ocs.indaba.controlpanel.controller.notif.NotificationsController.java

public String getTypeTokens() {

    JSONObject root = new JSONObject();

    try {//from  www .j a  v  a2  s .  c o m
        logger.debug("\nEnter getTypeTokens");
        printURLRequestQuery();

        List<NotificationType> nTypes = notificationItemSrvc.getNotificationTypes();
        JSONArray typeArr = new JSONArray();
        root.put("ntypes", typeArr);
        if (nTypes != null && !nTypes.isEmpty()) {
            for (NotificationType nt : nTypes) {
                JSONObject jsonObj = new JSONObject();
                jsonObj.put("id", nt.getId());
                jsonObj.put("category", nt.getCategory());
                typeArr.add(jsonObj);
            }
        }
        List<Tokenset> tklist = notificationItemSrvc.getTokensets();
        JSONArray categoryArr = new JSONArray();
        root.put("categories", categoryArr);
        if (tklist != null && !tklist.isEmpty()) {
            for (Tokenset tk : tklist) {
                JSONObject jsonObj = new JSONObject();
                jsonObj.put("id", tk.getId());
                jsonObj.put("tokens", tk.getTokens());
                jsonObj.put("category", tk.getCatgeory());
                categoryArr.add(jsonObj);
            }
        }
        super.sendResponseJson(root);

        return RESULT_EMPTY;
    } finally {
        logger.debug("\nExit getTypeTokens" + root + "\n");
    }
}

From source file:at.ac.tuwien.dsg.quelle.elasticityQuantification.requirements.ServiceUnitConfigurationSolution.java

public JSONObject toJSON() {
    JSONObject jsonDescription = new JSONObject();
    jsonDescription.put("serviceUnit", serviceUnit.getName());

    //quality options
    {//from w w w. j  a va  2  s. c om
        JSONArray array = new JSONArray();
        for (RequirementsMatchingEngine.RequirementsMatchingReport<Quality> qualityReport : chosenQualityOptions) {

            Quality quality = qualityReport.getConcreteConfiguration();
            JSONObject qualityDescription = new JSONObject();
            jsonDescription.put("quality", quality.getName());
            JSONArray qualityProperties = new JSONArray();

            for (Map.Entry<Metric, MetricValue> property : quality.getProperties().entrySet()) {
                JSONObject jsonPropertyDescription = new JSONObject();
                jsonPropertyDescription.put("property",
                        property.getKey().getName() + " [" + property.getKey().getMeasurementUnit() + "]");
                jsonPropertyDescription.put("value", property.getValue().getValueRepresentation());
                qualityProperties.add(jsonPropertyDescription);
            }
            qualityDescription.put("properties", qualityProperties);
            array.add(qualityDescription);
        }

        if (!array.isEmpty()) {
            jsonDescription.put("optionalQualitiesRecommended", array);
        }
    }

    //resource options
    {
        JSONArray array = new JSONArray();
        for (RequirementsMatchingEngine.RequirementsMatchingReport<Resource> qualityReport : chosenResourceOptions) {

            Resource quality = qualityReport.getConcreteConfiguration();
            JSONObject qualityDescription = new JSONObject();
            jsonDescription.put("resource", quality.getName());
            JSONArray qualityProperties = new JSONArray();

            for (Map.Entry<Metric, MetricValue> property : quality.getProperties().entrySet()) {
                JSONObject jsonPropertyDescription = new JSONObject();
                jsonPropertyDescription.put("property",
                        property.getKey().getName() + " [" + property.getKey().getMeasurementUnit() + "]");
                jsonPropertyDescription.put("value", property.getValue().getValueRepresentation());
                qualityProperties.add(jsonPropertyDescription);
            }
            qualityDescription.put("resources", qualityProperties);
            array.add(qualityDescription);
        }

        if (!array.isEmpty()) {
            jsonDescription.put("optionalResourcesRecommended", array);
        }
    }

    //mandatory service units
    {
        JSONArray array = new JSONArray();
        for (ServiceUnitConfigurationSolution configurationSolution : mandatoryAssociatedServiceUnits) {
            array.add(configurationSolution.toJSON());
        }
        if (!array.isEmpty()) {
            jsonDescription.put("mandatoryAssociatedServiceUnitsRecommendedConfigurations", array);
        }
    }

    //optional service units
    {
        JSONArray array = new JSONArray();
        for (ServiceUnitConfigurationSolution configurationSolution : optionallyAssociatedServiceUnits) {
            array.add(configurationSolution.toJSON());
        }
        if (!array.isEmpty()) {
            jsonDescription.put("optionalAssociatedServiceUnitsRecommendedConfigurations", array);
        }
    }

    return jsonDescription;
}

From source file:jp.aegif.nemaki.rest.GroupResource.java

@SuppressWarnings("unchecked")
@GET/* ww w  .j a va2  s . c om*/
@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();

    List<Group> groupList;
    try {
        groupList = principalService.getGroups(repositoryId);
        for (Group group : groupList) {
            JSONObject groupJSON = convertGroupToJson(group);
            listJSON.add(groupJSON);
        }
        result.put(ITEM_ALLGROUPS, listJSON);
    } catch (Exception ex) {
        ex.printStackTrace();
        addErrMsg(errMsg, ITEM_ALLGROUPS, ErrorCode.ERR_LIST);
    }
    result = makeResult(status, result, errMsg);
    return result.toString();
}

From source file:net.duckling.ddl.web.controller.team.ConfigTeamController.java

private JSONArray transferJSONArray(List<String> list) {
    JSONArray arr = new JSONArray();
    for (String s : list) {
        arr.add(s);
    }//from   w w w. j a v a2  s  .  c  o  m
    return arr;
}

From source file:net.duckling.ddl.web.controller.LynxSearchController.java

private String getJSONFromMap(String baseTagURL, Map<Integer, String> map) {
    JSONArray array = new JSONArray();
    if (null != map && !map.isEmpty()) {

        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            JSONObject obj = new JSONObject();
            obj.put("id", entry.getKey());
            obj.put("title", entry.getValue());
            obj.put("tagurl", baseTagURL);
            array.add(obj);
        }/*  ww w. j  a  v  a2s .c om*/
    }
    return array.toJSONString();
}

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

@SuppressWarnings("unchecked")
public void serveResource(ResourceRequest request, ResourceResponse response)
        throws PortletException, IOException {

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

    if (sraction != null && sraction.equals("save_params")) {

        Map<String, String> key = new HashMap<>();

        String genomeId = request.getParameter("genomeId");
        String taxonId = "";
        String cType = request.getParameter("context_type");
        String cId = request.getParameter("context_id");
        if (cType != null && cId != null && cType.equals("taxon") && !cId.equals("")) {
            taxonId = cId;//from w w w . ja  v  a 2 s.com
        }
        String keyword = request.getParameter("keyword");
        String state = request.getParameter("state");
        String ncbi_taxon_id = request.getParameter("ncbi_taxon_id");

        if (genomeId != null && !genomeId.equalsIgnoreCase("")) {
            key.put("genomeId", genomeId);
        }
        if (!taxonId.equalsIgnoreCase("")) {
            key.put("taxonId", taxonId);
        }
        if (keyword != null) {
            key.put("keyword", keyword.trim());
        }
        if (ncbi_taxon_id != null) {
            key.put("ncbi_taxon_id", ncbi_taxon_id);
        }
        if (state != null) {
            key.put("state", state);
        }
        long pk = (new Random()).nextLong();

        SessionHandler.getInstance().set(SessionHandler.PREFIX + pk, jsonWriter.writeValueAsString(key));

        PrintWriter writer = response.getWriter();
        writer.write("" + pk);
        writer.close();

    } else {

        String need = request.getParameter("need");
        JSONObject jsonResult = new JSONObject();

        switch (need) {
        case "0": {
            // Experiments
            String pk = request.getParameter("pk");
            Map data = processExperimentTab(request);

            Map<String, String> key = (Map) data.get("key");
            int numFound = (Integer) data.get("numFound");
            List<Map> experiments = (List<Map>) data.get("experiments");

            JSONArray docs = new JSONArray();
            for (Map item : experiments) {
                JSONObject doc = new JSONObject();
                doc.putAll(item);
                docs.add(doc);
            }

            if (data.containsKey("facets")) {
                JSONObject facets = FacetHelper.formatFacetTree((Map) data.get("facets"));
                key.put("facets", facets.toJSONString());
                SessionHandler.getInstance().set(SessionHandler.PREFIX + pk,
                        jsonWriter.writeValueAsString(key));
            }

            jsonResult.put("results", docs);
            jsonResult.put("total", numFound);

            response.setContentType("application/json");
            PrintWriter writer = response.getWriter();
            writer.write(jsonResult.toString());
            writer.close();

            break;
        }
        case "1": {
            // Comparisons
            Map data = processComparisonTab(request);

            int numFound = (Integer) data.get("numFound");
            List<Map> comparisons = (List<Map>) data.get("comparisons");

            JSONArray docs = new JSONArray();
            for (Map item : comparisons) {
                JSONObject doc = new JSONObject();
                doc.putAll(item);
                docs.add(doc);
            }

            //            key.put("keyword", orig_keyword);

            jsonResult.put("results", docs);
            jsonResult.put("total", numFound);

            response.setContentType("application/json");
            PrintWriter writer = response.getWriter();
            jsonResult.writeJSONString(writer);
            writer.close();

            break;
        }
        case "tree": {

            String pk = request.getParameter("pk");
            Map<String, String> key = jsonReader
                    .readValue(SessionHandler.getInstance().get(SessionHandler.PREFIX + pk));
            String state;

            if (key.containsKey("state")) {
                state = key.get("state");
            } else {
                state = request.getParameter("state");
            }

            key.put("state", state);

            SessionHandler.getInstance().set(SessionHandler.PREFIX + pk, jsonWriter.writeValueAsString(key));

            JSONArray tree = new JSONArray();
            try {
                if (key.containsKey("facets") && !key.get("facets").equals("{}")) {

                    JSONObject facet_fields = (JSONObject) new JSONParser().parse(key.get("facets"));
                    DataApiHandler dataApi = new DataApiHandler(request);
                    tree = FacetHelper.processStateAndTree(dataApi, SolrCore.TRANSCRIPTOMICS_EXPERIMENT, key,
                            need, facet_fields, key.get("facet"), state, null, 4);
                }
            } catch (ParseException e) {
                LOGGER.error(e.getMessage(), e);
            }

            response.setContentType("application/json");
            PrintWriter writer = response.getWriter();
            tree.writeJSONString(writer);
            writer.close();
            break;
        }
        case "download": {
            List<String> tableHeader = new ArrayList<>();
            List<String> tableField = new ArrayList<>();
            JSONArray tableSource = new JSONArray();

            String fileName = "Transcriptomics";
            String fileFormat = request.getParameter("fileformat");

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

            switch (aT) {
            case "0": {
                // experiments
                Map data = processExperimentTab(request);
                List<Map> experiments = (List<Map>) data.get("experiments");

                for (Map item : experiments) {
                    JSONObject doc = new JSONObject();
                    doc.putAll(item);
                    tableSource.add(doc);
                }

                tableHeader.addAll(DownloadHelper.getHeaderForTranscriptomicsExperiment());
                tableField.addAll(DownloadHelper.getFieldsForTranscriptomicsExperiment());
                break;
            }
            case "1": {
                // comparisons
                Map data = processComparisonTab(request);
                List<Map> comparisons = (List<Map>) data.get("comparisons");

                for (Map item : comparisons) {
                    JSONObject doc = new JSONObject();
                    doc.putAll(item);
                    tableSource.add(doc);
                }

                tableHeader.addAll(DownloadHelper.getHeaderForTranscriptomicsComparison());
                tableField.addAll(DownloadHelper.getFieldsForTranscriptomicsComparison());
                break;
            }
            }

            ExcelHelper excel = new ExcelHelper("xssf", tableHeader, tableField, tableSource);
            excel.buildSpreadsheet();

            if (fileFormat.equalsIgnoreCase("xlsx")) {
                response.setContentType("application/octetstream");
                response.addProperty("Content-Disposition",
                        "attachment; filename=\"" + fileName + "." + fileFormat + "\"");

                excel.writeSpreadsheettoBrowser(response.getPortletOutputStream());
            } else if (fileFormat.equalsIgnoreCase("txt")) {

                response.setContentType("application/octetstream");
                response.addProperty("Content-Disposition",
                        "attachment; filename=\"" + fileName + "." + fileFormat + "\"");

                response.getPortletOutputStream().write(excel.writeToTextFile().getBytes());
            }
            break;
        }
        }
    }
}

From source file:modelo.ParametrizacionManagers.DocumentacionRequerida.java

/**
  * //from  ww  w  .  jav a 2 s.  com
  * Obtiene la informacion de un documento requerido y
  * guarda todo en un JSONArray para entregarselo a la vista.
  * 
  * @param codigo
  * @param tipoInforme
  * @return JSONArray
  * @throws SQLException 
  */
public JSONArray getDocumentacionRequerida(Integer codigo, Integer tipoInforme) throws SQLException {

    //Ejecutamos la consulta y obtenemos el ResultSet
    SeleccionarDocumentacionRequerida select = new SeleccionarDocumentacionRequerida();
    ResultSet rset = select.getDocumentacionRequerida(codigo, tipoInforme);

    //Creamos los JSONArray para guardar los objetos JSON
    JSONArray jsonArray = 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("codigo", rset.getString("CODIGO"));
        jsonObject.put("descripcion", rset.getString("DESCRIPCION"));
        jsonObject.put("tipoInforme", rset.getString("TIPO_INFORME"));
        jsonObject.put("codTipoInforme", rset.getString("COD_TIPO_INFORME"));

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

    }

    select.desconectar();
    return jsonArray;

}