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:com.rackspacecloud.blueflood.outputs.serializers.JSONBasicRollupsOutputSerializer.java

protected JSONArray transformDataToJSONArray(MetricData metricData, Set<MetricStat> filterStats)
        throws SerializationException {
    Points points = metricData.getData();
    final JSONArray data = new JSONArray();
    final Set<Map.Entry<Long, Points.Point>> dataPoints = points.getPoints().entrySet();
    for (Map.Entry<Long, Points.Point> point : dataPoints) {
        data.add(toJSON(point.getKey(), point.getValue(), metricData.getUnit(), filterStats));
    }//w  ww.j  a  v  a  2  s.c  om

    return data;
}

From source file:com.piusvelte.hydra.ApiServlet.java

public void doDelete(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ConnectionManager connMgr = ConnectionManager.getInstance(getServletContext());
    if (connMgr.isAuthenticated(request.getParameter(PARAM_TOKEN))) {
        HydraRequest hydraRequest;/*from www  . j  av a2  s  .c o m*/
        try {
            hydraRequest = HydraRequest.fromPut(request);
        } catch (Exception e) {
            JSONObject j = new JSONObject();
            JSONArray errors = new JSONArray();
            errors.add(e.getMessage());
            response.setStatus(402);
            j.put("errors", errors);
            response.getWriter().write(j.toJSONString());
            return;
        }
        DatabaseConnection databaseConnection = null;
        connMgr.queueDatabaseRequest(hydraRequest.database);
        try {
            while (databaseConnection == null)
                databaseConnection = connMgr.getDatabaseConnection(hydraRequest.database);
        } catch (Exception e) {
            e.printStackTrace();
        }
        connMgr.dequeueDatabaseRequest(hydraRequest.database);
        if (databaseConnection != null) {
            response.getWriter().write(
                    databaseConnection.delete(hydraRequest.target, hydraRequest.selection).toJSONString());
            databaseConnection.release();
        } else if (hydraRequest.queueable) {
            JSONObject j = new JSONObject();
            JSONArray errors = new JSONArray();
            errors.add("no database connection");
            connMgr.queueRequest(hydraRequest.toJSONString());
            errors.add("queued");
            response.setStatus(200);
            j.put("errors", errors);
            response.getWriter().write(j.toJSONString());
        } else {
            response.setStatus(502);
            JSONObject j = new JSONObject();
            JSONArray errors = new JSONArray();
            errors.add("no database connection available");
            j.put("errors", errors);
            response.getWriter().write(j.toJSONString());
        }
        connMgr.cleanDatabaseConnections(hydraRequest.database);
    } else {
        response.setStatus(401);
    }
}

From source file:com.piusvelte.hydra.MSSQLConnection.java

private JSONArray getResult(ResultSet rs) throws SQLException {
    JSONArray rows = new JSONArray();
    ResultSetMetaData rsmd = rs.getMetaData();
    String[] columnsArr = new String[rsmd.getColumnCount()];
    for (int c = 0, l = columnsArr.length; c < l; c++)
        columnsArr[c] = rsmd.getColumnName(c);
    while (rs.next()) {
        JSONArray rowData = new JSONArray();
        for (String column : columnsArr)
            rowData.add((String) rs.getObject(column));
        rows.add(rowData);//from  www  .j  a v a 2s  .c  o  m
    }
    return rows;
}

From source file:generate.ShowArticlesAction.java

public String execute() throws ClassNotFoundException, SQLException, IOException {
    List<DBObject> documents = new ArrayList<>();
    System.out.println("Mark 0");
    try {/*ww  w .  j  av  a  2  s.c o m*/
        MongoClient mongo = new MongoClient();
        DB db = mongo.getDB("Major");
        DBCollection collection = db.getCollection("ConceptMap");
        DBCursor cursor = collection.find();
        documents = cursor.toArray();
        cursor.close();
    } catch (MongoException e) {
        System.out.println("ERRRRRORRR: " + e.getMessage());
        return ERROR;
    } catch (UnknownHostException ex) {
        Logger.getLogger(MapGenerateAction.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.out.println("Mark 1");
    Map<String, ArrayList<String>> chap_to_section = new HashMap<>();
    Map<String, String> id_to_section = new HashMap<>();
    for (DBObject document : documents) {
        String c_name = document.get("ChapterName").toString();
        boolean has_key = chap_to_section.containsKey(c_name);
        ArrayList<String> sections = new ArrayList<>();
        sections.add(document.get("SectionName").toString());
        if (has_key) {
            sections.addAll(chap_to_section.get(c_name));
            chap_to_section.put(c_name, sections);
        } else {
            chap_to_section.put(c_name, sections);
        }
        id_to_section.put(document.get("SectionName").toString(), document.get("UniqueID").toString());
    }
    FileWriter file = null;
    try {
        file = new FileWriter("/home/chanakya/NetBeansProjects/Concepto/web/Chapters_Sections.json");
    } catch (IOException ex) {
        Logger.getLogger(ShowArticlesAction.class.getName()).log(Level.SEVERE, null, ex);
    }
    JSONArray jarr = new JSONArray();

    for (String key : chap_to_section.keySet()) {
        JSONObject jobj = new JSONObject();
        JSONArray arr = new JSONArray();

        for (String val : chap_to_section.get(key)) {
            JSONObject temp = new JSONObject();
            temp.put("name", val);
            temp.put("id", id_to_section.get(val).toString());
            arr.add(temp);
        }
        jobj.put("sname", arr);
        jobj.put("cname", key);
        jarr.add(jobj);
    }
    System.out.println("Mark 2");
    //JSONObject obj = new JSONObject();
    //obj.put("cmap", jarr);
    file.write(jarr.toJSONString());
    file.flush();
    file.close();
    System.out.println("Mark 3");
    return SUCCESS;
}

From source file:ch.zhaw.icclab.tnova.expressionsolver.Base.java

@GET
@Produces(MediaType.APPLICATION_JSON)//from  w w  w  .ja  va 2s  .com
public String homePage() {
    KPI.api_calls += 1;
    JSONObject obj = new JSONObject();
    obj.put("src", "t-nova expression evaluation service");
    obj.put("msg", "api summary list");
    JSONArray apiList = new JSONArray();
    JSONObject api = new JSONObject();
    api.put("uri", "/");
    api.put("method", "GET");
    api.put("purpose", "capability discovery");
    apiList.add(api);

    api = new JSONObject();
    api.put("uri", "/template/");
    api.put("method", "GET");
    api.put("purpose", "list of registered expression templates");
    apiList.add(api);

    api = new JSONObject();
    api.put("uri", "/template/");
    api.put("method", "POST");
    api.put("purpose", "registration of a new expression template");
    apiList.add(api);

    api = new JSONObject();
    api.put("uri", "/template/{id}");
    api.put("method", "GET");
    api.put("purpose", "get specific expression template details");
    apiList.add(api);

    api = new JSONObject();
    api.put("uri", "/expression/{id}");
    api.put("method", "DELETE");
    api.put("purpose", "delete specific expression template, all expression instantiation will be deleted");
    apiList.add(api);

    api = new JSONObject();
    api.put("uri", "/expression/");
    api.put("method", "GET");
    api.put("purpose", "list of registered expressions");
    apiList.add(api);

    api = new JSONObject();
    api.put("uri", "/expression/");
    api.put("method", "POST");
    api.put("purpose", "register a new expression");
    apiList.add(api);

    api = new JSONObject();
    api.put("uri", "/expression/{id}");
    api.put("method", "GET");
    api.put("purpose", "get specific expression details");
    apiList.add(api);

    api = new JSONObject();
    api.put("uri", "/expression/{id}");
    api.put("method", "PUT");
    api.put("purpose", "update a specific expression");
    apiList.add(api);

    api = new JSONObject();
    api.put("uri", "/expression/{id}");
    api.put("method", "POST");
    api.put("purpose", "execute a specific expression");
    apiList.add(api);

    api = new JSONObject();
    api.put("uri", "/expression/{id}");
    api.put("method", "DELETE");
    api.put("purpose", "delete a specific expression");
    apiList.add(api);

    api = new JSONObject();
    api.put("uri", "/kpi");
    api.put("method", "GET");
    api.put("purpose", "get the service key runtime metrics");
    apiList.add(api);

    api = new JSONObject();
    api.put("uri", "/otfly/");
    api.put("method", "POST");
    api.put("purpose", "on the fly stateless expression evaluation");
    api.put("op-supported", "lt, gt, add, max, min, avg");
    apiList.add(api);

    obj.put("api", apiList);

    logger.info("URI:/ Method:GET Request procesed.");
    KPI.api_calls_success += 1;
    return obj.toJSONString();
}

From source file:com.piusvelte.hydra.ApiServlet.java

public void doPut(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ConnectionManager connMgr = ConnectionManager.getInstance(getServletContext());
    if (connMgr.isAuthenticated(request.getParameter(PARAM_TOKEN))) {
        HydraRequest hydraRequest;/*  w  w  w  . j  a  va 2 s  .  c om*/
        try {
            hydraRequest = HydraRequest.fromPut(request);
        } catch (Exception e) {
            JSONObject j = new JSONObject();
            JSONArray errors = new JSONArray();
            errors.add(e.getMessage());
            response.setStatus(402);
            j.put("errors", errors);
            response.getWriter().write(j.toJSONString());
            return;
        }
        DatabaseConnection databaseConnection = null;
        connMgr.queueDatabaseRequest(hydraRequest.database);
        try {
            while (databaseConnection == null)
                databaseConnection = connMgr.getDatabaseConnection(hydraRequest.database);
        } catch (Exception e) {
            e.printStackTrace();

        }
        connMgr.dequeueDatabaseRequest(hydraRequest.database);
        if (databaseConnection != null) {
            response.getWriter().write(databaseConnection.update(hydraRequest.target, hydraRequest.columns,
                    hydraRequest.values, hydraRequest.selection).toJSONString());
            databaseConnection.release();
        } else if (hydraRequest.queueable) {
            JSONObject j = new JSONObject();
            JSONArray errors = new JSONArray();
            errors.add("no database connection");
            connMgr.queueRequest(hydraRequest.toJSONString());
            errors.add("queued");
            response.setStatus(200);
            j.put("errors", errors);
            response.getWriter().write(j.toJSONString());
        } else {
            response.setStatus(502);
            JSONObject j = new JSONObject();
            JSONArray errors = new JSONArray();
            errors.add("no database connection available");
            j.put("errors", errors);
            response.getWriter().write(j.toJSONString());
        }
        connMgr.cleanDatabaseConnections(hydraRequest.database);
    } else {
        response.setStatus(401);
    }
}

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

@SuppressWarnings("unchecked")
public void serveResource(ResourceRequest request, ResourceResponse response)
        throws PortletException, IOException {
    String callType = request.getParameter("callType");

    if (callType != null) {
        Map<String, String> key = new HashMap<>();
        if (callType.equals("saveState")) {
            String genomeIds = request.getParameter("genomeIds");
            String familyIds = request.getParameter("familyIds");
            String familyType = request.getParameter("familyType");

            key.put("genomeIds", genomeIds);
            key.put("familyIds", familyIds);
            key.put("familyType", familyType);

            Random g = new Random();
            long pk = g.nextLong();

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

            PrintWriter writer = response.getWriter();
            writer.write("" + pk);
            writer.close();/*w w w . j av  a2 s.  c om*/

        } else if (callType.equals("getData")) {

            Map data = processFeatureTab(request);
            int numFound = (Integer) data.get("numFound");
            List<GenomeFeature> features = (List<GenomeFeature>) data.get("features");

            JSONArray docs = new JSONArray();
            for (GenomeFeature feature : features) {
                docs.add(feature.toJSONObject());
            }

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

            response.setContentType("application/json");
            PrintWriter writer = response.getWriter();
            jsonResult.writeJSONString(writer);
            writer.close();
        } else if (callType.equals("download")) {

            List<String> tableHeader = new ArrayList<>();
            List<String> tableField = new ArrayList<>();
            JSONArray tableSource = new JSONArray();

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

            // features
            Map data = processFeatureTab(request);
            List<GenomeFeature> features = (List<GenomeFeature>) data.get("features");

            for (GenomeFeature feature : features) {
                tableSource.add(feature.toJSONObject());
            }

            tableHeader.addAll(DownloadHelper.getHeaderForFeatures());
            tableField.addAll(DownloadHelper.getFieldsForFeatures());

            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());
            }
        }
    }
}

From source file:org.kitodo.data.index.elasticsearch.type.ProjectType.java

@SuppressWarnings("unchecked")
@Override//from www. j a va  2 s.  c  o  m
public HttpEntity createDocument(Project project) {

    LinkedHashMap<String, String> orderedProjectMap = new LinkedHashMap<>();
    orderedProjectMap.put("name", project.getTitle());
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    String startDate = project.getStartDate() != null ? dateFormat.format(project.getStartDate()) : null;
    orderedProjectMap.put("startDate", startDate);
    String endDate = project.getEndDate() != null ? dateFormat.format(project.getEndDate()) : null;
    orderedProjectMap.put("endDate", endDate);
    String numberOfPages = project.getNumberOfPages() != null ? project.getNumberOfPages().toString() : "null";
    orderedProjectMap.put("numberOfPages", numberOfPages);
    String numberOfVolumes = project.getNumberOfVolumes() != null ? project.getNumberOfVolumes().toString()
            : "null";
    orderedProjectMap.put("numberOfVolumes", numberOfVolumes);
    String archived = project.getProjectIsArchived() != null ? project.getProjectIsArchived().toString()
            : "null";
    orderedProjectMap.put("archived", archived);

    JSONObject projectObject = new JSONObject(orderedProjectMap);

    JSONArray processes = new JSONArray();
    List<Process> projectProcesses = project.getProcesses();
    for (Process process : projectProcesses) {
        JSONObject processObject = new JSONObject();
        processObject.put("id", process.getId().toString());
        processes.add(processObject);
    }
    projectObject.put("processes", processes);

    JSONArray users = new JSONArray();
    List<User> projectUsers = project.getUsers();
    for (User user : projectUsers) {
        JSONObject userObject = new JSONObject();
        userObject.put("id", user.getId().toString());
        users.add(userObject);
    }
    projectObject.put("users", users);

    JSONArray projectFileGroups = new JSONArray();
    List<ProjectFileGroup> projectProjectFileGroups = project.getProjectFileGroups();
    for (ProjectFileGroup projectFileGroup : projectProjectFileGroups) {
        JSONObject projectFileGroupObject = new JSONObject();
        projectFileGroupObject.put("name", projectFileGroup.getName());
        projectFileGroupObject.put("path", projectFileGroup.getPath());
        projectFileGroupObject.put("mimeType", projectFileGroup.getMimeType());
        projectFileGroupObject.put("suffix", projectFileGroup.getSuffix());
        projectFileGroupObject.put("folder", projectFileGroup.getFolder());
        projectFileGroups.add(projectFileGroupObject);
    }
    projectObject.put("projectFileGroups", projectFileGroups);

    return new NStringEntity(projectObject.toJSONString(), ContentType.APPLICATION_JSON);
}

From source file:com.pinterest.rocksplicator.ConfigGenerator.java

private void generateShardConfig() {
    HelixAdmin admin = helixManager.getClusterManagmentTool();

    List<String> resources = admin.getResourcesInCluster(clusterName);

    Set<String> existingHosts = new HashSet<String>();

    // compose cluster config
    JSONObject config = new JSONObject();
    for (String resource : resources) {
        // Resources starting with PARTICIPANT_LEADER is for HelixCustomCodeRunner
        if (resource.startsWith("PARTICIPANT_LEADER")) {
            continue;
        }/*  ww w  . ja v a 2s.  com*/

        ExternalView externalView = admin.getResourceExternalView(clusterName, resource);
        Set<String> partitions = externalView.getPartitionSet();

        // compose resource config
        JSONObject resourceConfig = new JSONObject();
        String partitionsStr = externalView.getRecord().getSimpleField("NUM_PARTITIONS");
        resourceConfig.put("num_shards", Integer.parseInt(partitionsStr));

        // build host to partition list map
        Map<String, List<String>> hostToPartitionList = new HashMap<String, List<String>>();
        for (String partition : partitions) {
            String[] parts = partition.split("_");
            String partitionNumber = String.format("%05d", Integer.parseInt(parts[parts.length - 1]));
            Map<String, String> hostToState = externalView.getStateMap(partition);
            for (Map.Entry<String, String> entry : hostToState.entrySet()) {
                existingHosts.add(entry.getKey());

                if (disabledHosts.contains(entry.getKey())) {
                    // exclude disabled hosts from the shard map config
                    continue;
                }

                String state = entry.getValue();
                if (!state.equalsIgnoreCase("ONLINE") && !state.equalsIgnoreCase("MASTER")
                        && !state.equalsIgnoreCase("SLAVE")) {
                    // Only ONLINE, MASTER and SLAVE states are ready for serving traffic
                    continue;
                }

                String hostWithDomain = getHostWithDomain(entry.getKey());
                List<String> partitionList = hostToPartitionList.get(hostWithDomain);
                if (partitionList == null) {
                    partitionList = new ArrayList<String>();
                    hostToPartitionList.put(hostWithDomain, partitionList);
                }

                if (state.equalsIgnoreCase("SLAVE")) {
                    partitionList.add(partitionNumber + ":S");
                } else if (state.equalsIgnoreCase("MASTER")) {
                    partitionList.add(partitionNumber + ":M");
                } else {
                    partitionList.add(partitionNumber);
                }
            }
        }

        // Add host to partition list map to the resource config
        for (Map.Entry<String, List<String>> entry : hostToPartitionList.entrySet()) {
            JSONArray jsonArray = new JSONArray();
            for (String p : entry.getValue()) {
                jsonArray.add(p);
            }

            resourceConfig.put(entry.getKey(), jsonArray);
        }

        // add the resource config to the cluster config
        config.put(resource, resourceConfig);
    }

    // remove host that doesn't exist in the ExternalView from hostToHostWithDomain
    hostToHostWithDomain.keySet().retainAll(existingHosts);

    String newContent = config.toString();
    if (lastPostedContent != null && lastPostedContent.equals(newContent)) {
        LOG.error("Identical external view observed, skip updating config.");
        return;
    }

    // Write the config to ZK
    LOG.error("Generating a new shard config...");

    this.dataParameters.remove("content");
    this.dataParameters.put("content", newContent);
    HttpPost httpPost = new HttpPost(this.postUrl);
    try {
        httpPost.setEntity(new StringEntity(this.dataParameters.toString()));
        HttpResponse response = new DefaultHttpClient().execute(httpPost);
        if (response.getStatusLine().getStatusCode() == 200) {
            lastPostedContent = newContent;
            LOG.error("Succeed to generate a new shard config, sleep for 2 seconds");
            TimeUnit.SECONDS.sleep(2);
        } else {
            LOG.error(response.getStatusLine().getReasonPhrase());
        }
    } catch (Exception e) {
        LOG.error("Failed to post the new config", e);
    }
}

From source file:com.piusvelte.hydra.ApiServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (request.getParameter(PARAM_TOKEN) == null)
        response.getWriter().write(/*from   w  w w.j  av a2  s  .  c  om*/
                "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><title>Hydra</title></head><body><h3>Hydra API</h3>");
    else {
        ServletContext ctx = getServletContext();
        HydraRequest hydraRequest;
        try {
            hydraRequest = HydraRequest.fromGet(request);
        } catch (Exception e) {
            ctx.log(e.getMessage());
            JSONObject j = new JSONObject();
            JSONArray errors = new JSONArray();
            errors.add(e.getMessage());
            response.setStatus(402);
            j.put("errors", errors);
            response.getWriter().write(j.toJSONString());
            return;
        }
        ConnectionManager connMgr = ConnectionManager.getInstance(ctx);
        if (connMgr.isAuthenticated(request.getParameter(PARAM_TOKEN))) {
            if (hydraRequest.hasDatabase()) {
                if (hydraRequest.hasTarget()) {
                    DatabaseConnection databaseConnection = null;
                    connMgr.queueDatabaseRequest(hydraRequest.database);
                    try {
                        while (databaseConnection == null)
                            databaseConnection = connMgr.getDatabaseConnection(hydraRequest.database);
                    } catch (Exception e) {
                        ctx.log("Hydra: " + e.getMessage());
                    }
                    connMgr.dequeueDatabaseRequest(hydraRequest.database);
                    if (databaseConnection != null) {
                        response.getWriter().write(databaseConnection
                                .query(hydraRequest.target, hydraRequest.columns, hydraRequest.selection)
                                .toJSONString());
                        databaseConnection.release();
                    } else if (hydraRequest.queueable) {
                        JSONObject j = new JSONObject();
                        JSONArray errors = new JSONArray();
                        errors.add("no database connection");
                        connMgr.queueRequest(hydraRequest.toJSONString());
                        errors.add("queued");
                        response.setStatus(200);
                        j.put("errors", errors);
                        response.getWriter().write(j.toJSONString());
                    } else {
                        response.setStatus(502);
                    }
                    connMgr.cleanDatabaseConnections(hydraRequest.database);
                } else {
                    response.getWriter().write(connMgr.getDatabase(hydraRequest.database).toJSONString());
                }
            } else {
                response.getWriter().write(connMgr.getDatabases().toJSONString());
            }
        } else {
            ctx.log("not authenticated");
            JSONObject j = new JSONObject();
            JSONArray errors = new JSONArray();
            errors.add("not authenticated");
            j.put("errors", errors);
            response.getWriter().write(j.toJSONString());
            response.setStatus(401);
        }
    }
}