Example usage for org.json.simple JSONArray toJSONString

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

Introduction

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

Prototype

public String toJSONString() 

Source Link

Usage

From source file:com.p000ison.dev.simpleclans2.exceptions.handling.ExceptionReporterTask.java

@Override
@SuppressWarnings("unchecked")
public void run() {
    if (queue.isEmpty()) {
        return;//ww w  .j  a  va  2  s  .c o  m
    }

    JSONArray reports = new JSONArray();

    ExceptionReport report;
    int i = 0;
    while ((report = queue.poll()) != null && i <= MAX_REPORTS_PER_PUSH) {
        i++;
        reports.add(report.getJSONObject());
    }

    try {
        PHPConnection connection = new PHPConnection(PROTOCOL, HOST, PORT, FILE, true);
        connection.write("report=" + reports.toJSONString());
        String response = connection.read();
        if (response != null && !response.isEmpty()) {
            throw new IOException("Failed at pushing error reports: " + response);
        }
    } catch (IOException e) {
        Logging.debug(e, false);
    }
}

From source file:com.imagelake.android.category.Servlet_categories.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    PrintWriter out = response.getWriter();

    CategoriesDAOImp categoryDAOImp = new CategoriesDAOImp();
    JSONArray ja = new JSONArray();
    ArrayList<Categories> categoriesList = (ArrayList<Categories>) categoryDAOImp.listAllCategories();
    if (!categoriesList.isEmpty()) {
        for (Categories cc : categoriesList) {
            JSONObject jo = new JSONObject();
            jo.put("id", cc.getCategory_id());
            jo.put("cat", cc.getCategory());
            ja.add(jo);/*from w ww  .j  a  va2s  .co  m*/

        }
        out.write("json=" + ja.toJSONString());
    } else {

        JSONObject jo = new JSONObject();
        jo.put("id", 0);
        jo.put("cat", "No category found.");
        ja.add(jo);
        out.write("json=" + ja.toJSONString());

    }
}

From source file:au.edu.jcu.fascinator.portal.sso.shibboleth.roles.simple.SimpleShibbolethRoleManager.java

@Override
public List<String> getRolesList(JsonSessionState session) {
    List<String> toRet = new ArrayList<String>();
    if (cfg == null) {
        return toRet;
    }// w w  w.ja  v  a  2  s  .  c o  m
    JSONArray tmp, _tmp;
    JSONArray rule;
    ArrayList _attr;
    String attr, op;
    ShibSimpleRoleOperator operation;
    for (Object role : cfg.keySet()) {
        _tmp = (JSONArray) cfg.get(role);
        for (Object o : _tmp) {
            tmp = (JSONArray) o;

            logger.info(String.format("%s Array: %s", role, tmp.toJSONString()));
            int entryCount = 0;
            for (Object _rule : tmp) {
                if (_rule instanceof JSONArray) {
                    rule = (JSONArray) _rule;
                    _attr = (ArrayList) session.get(rule.get(ATTR_POS).toString());
                    if (_attr != null) {
                        logger.trace("Found attr: " + rule.get(ATTR_POS) + " in session.");
                        operation = operations.get(op = rule.get(OP_POS).toString());
                        if (operation != null) {
                            for (Object s : _attr) {
                                attr = (String) s;
                                if (operation.doOperation(rule.get(VALUE_POS).toString(), attr)) {
                                    entryCount++;
                                }
                            }
                        } else {
                            logger.error(String.format("The operation: %s is unknown, skipping.", op));
                        }
                    }
                } else {
                    logger.error(
                            String.format("The %s role is not correctly configured fo the %s role manager.",
                                    role, SimpleShibbolethRoleManager.class.getName()));
                }
            }
            logger.trace(String.format("Entry Count: %d Size: %d", entryCount, tmp.size()));
            if (entryCount == tmp.size()) {
                toRet.add(role.toString());
            }
        }
    }
    return toRet;
}

From source file:geo.controller.LoadDataServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w w w.  j  a va 2  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
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");
    PrintWriter out = response.getWriter();

    try {
        ArrayList<Transaction> transactionList = TransactionDAO.getTransactionList();

        JSONArray jsonArray = new JSONArray();
        int index = 0;

        //hardcode to remove error in geocode
        for (int i = 0; i < transactionList.size(); i++) {
            if (transactionList.get(i).postalCode.equals("158744")) {
                continue;
            }
            jsonArray.add(index++, transactionList.get(i).getJSONObject());
        }

        out.println(jsonArray.toJSONString());

    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

From source file:azkaban.web.pages.IndexServlet.java

@SuppressWarnings("unchecked")
private String getJSONJobsForFolder(FlowManager manager, String folder) {
    List<String> rootJobs = manager.getRootNamesByFolder(folder);
    Collections.sort(rootJobs);//from   ww w .j a  v a2s  .c o m

    JSONArray rootJobObj = new JSONArray();
    for (String root : rootJobs) {
        Flow flow = manager.getFlow(root);
        JSONObject flowObj = getJSONDependencyTree(flow);
        rootJobObj.add(flowObj);
    }

    return rootJobObj.toJSONString();
}

From source file:eu.juniper.MonitoringLib.java

private ArrayList<String> readJson(ArrayList<String> elementsList, JSONObject jsonObject, PrintWriter writer,
        String TagName) throws FileNotFoundException, IOException, ParseException {
    String appId = "";
    if (jsonObject.get(TagName) == null) {
        elementsList.add("null");
    } else {//from   ww w  .j  a va 2 s  .co  m
        String Objectscontent = jsonObject.get(TagName).toString();
        if (Objectscontent.startsWith("[{") && Objectscontent.endsWith("}]")) {
            JSONArray jsonArray = (JSONArray) jsonObject.get(TagName);

            for (int temp = 0; temp < jsonArray.size(); temp++) {
                System.out.println("Array:" + jsonArray.toJSONString());
                JSONObject jsonObjectResult = (JSONObject) jsonArray.get(temp);
                System.out.println("Result:" + jsonObjectResult.toJSONString());

                Set<String> jsonObjectResultKeySet = jsonObjectResult.keySet();
                System.out.println("KeySet:" + jsonObjectResultKeySet.toString());

                for (String s : jsonObjectResultKeySet) {
                    System.out.println(s);
                    readJson(elementsList, jsonObjectResult, writer, s);
                }
            }
        } else {
            appId = jsonObject.get(TagName).toString();
            elementsList.add(appId);
        }
    }
    return elementsList;
}

From source file:com.niles.excel2json.objects.ExcelFile.java

public void writeToJson(JSONArray myJSONArray) {
    String jsFilePath = folderPath + sheetName.replaceAll(" ", "") + ".js";
    String jsonFilePath = folderPath + sheetName.replaceAll(" ", "") + ".json";

    logger.info("Writing file {}", jsFilePath);

    try {//from w w w .j a  v  a2s  . co m
        // Create file
        FileWriter JSONFileStream = SystemTools.getFileWriter(jsFilePath);
        JSONFileStream.write("var " + sheetName.replaceAll("-", "").replaceAll(" ", "") + " = "
                + myJSONArray.toJSONString() + ";");
        // JSONFileStream.write(myJSONArray.toJSONString());
        JSONFileStream.flush();
        JSONFileStream.close();
    } catch (IOException ex) {
        logger.error("[{}]  Error writing JSON\r\n{}", jsFilePath, ex.getMessage());
    }

    logger.info("Writing file {}", jsonFilePath);

    try {
        // Create file
        FileWriter JSONFileStream = SystemTools.getFileWriter(jsonFilePath);
        JSONFileStream.write(myJSONArray.toJSONString());
        // JSONFileStream.write(myJSONArray.toJSONString());
        JSONFileStream.flush();
        JSONFileStream.close();
    } catch (IOException ex) {
        logger.error("[{}]  Error writing JSON\r\n{}", jsonFilePath, ex.getMessage());
    }
}

From source file:hoot.services.controllers.job.ExportJobResource.java

/**
 * <NAME>Export Service Job Execute</NAME>
 * <DESCRIPTION>//ww w.  ja  va  2s .  c  o m
 *    Asynchronous export service.
 * </DESCRIPTION>
 * <PARAMETERS>
 * <translation>
 *    Translation script name.
 * </translation>
 * <inputtype>
 *  [db | file] db means input from hoot db will be used. file mean a file path will be specified.
 * </inputtype>
 * <input>
 * Input name. for inputtype = db then specify name from hoot db. For inputtype=file, specify full path to a file.
 * </input>
 * <outputtype>
 *    [gdb | shp | wfs]. gdb will produce file gdb, shp will output shapefile. if outputtype = wfs then a wfs front end will be created
 * </outputtype>
 * <removereview>
 * Removes all unreviewed items. NOTE: removereview will alway be true.
 * </removereview>
 * </PARAMETERS>
 * <OUTPUT>
 *    Job ID
 * </OUTPUT>
 * <EXAMPLE>
 *    <URL>http://localhost:8080/hoot-services/job/export/execute</URL>
 *    <REQUEST_TYPE>POST</REQUEST_TYPE>
 *    <INPUT>
 * {
* "translation":"MGCP.js",
* "inputtype":"db",
* "input":"ToyTestA",
* "outputtype":"gdb",
* "removereview" : "false"
*
* }
 *   </INPUT>
 * <OUTPUT>{"jobid":"24d1400e-434e-45e0-9afe-372215490be2"}</OUTPUT>
 * </EXAMPLE>
 * @param params
 * @return
 */
@POST
@Path("/execute")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public Response process(String params) {
    String jobId = UUID.randomUUID().toString();
    jobId = "ex_" + jobId.replace("-", "");
    try {
        JSONArray commandArgs = parseParams(params);

        JSONObject arg = new JSONObject();
        arg.put("outputfolder", tempOutputPath + "/" + jobId);
        commandArgs.add(arg);

        arg = new JSONObject();
        arg.put("output", jobId);
        commandArgs.add(arg);

        String type = getParameterValue("outputtype", commandArgs);
        if (type != null && type.equalsIgnoreCase("wfs")) {
            arg = new JSONObject();
            arg.put("outputname", jobId);
            commandArgs.add(arg);

            String dbname = HootProperties.getProperty("dbName");
            String userid = HootProperties.getProperty("dbUserId");
            String pwd = HootProperties.getProperty("dbPassword");
            String host = HootProperties.getProperty("dbHost");
            String[] hostParts = host.split(":");

            String pgUrl = "host='" + hostParts[0] + "' port='" + hostParts[1] + "' user='" + userid
                    + "' password='" + pwd + "' dbname='" + wfsStoreDb + "'";

            arg = new JSONObject();
            arg.put("PG_URL", pgUrl);
            commandArgs.add(arg);

            JSONObject osm2orgCommand = _createPostBody(commandArgs);
            // this may need change in the future if we decided to use user defined ouputname..
            String outname = jobId;

            JSONArray wfsArgs = new JSONArray();
            JSONObject param = new JSONObject();
            param.put("value", outname);
            param.put("paramtype", String.class.getName());
            param.put("isprimitivetype", "false");
            wfsArgs.add(param);

            JSONObject prepareItemsForReviewCommand = _createReflectionSycJobReq(wfsArgs,
                    "hoot.services.controllers.wfs.WfsManager", "createWfsResource");

            JSONArray jobArgs = new JSONArray();
            jobArgs.add(osm2orgCommand);
            jobArgs.add(prepareItemsForReviewCommand);

            postChainJobRquest(jobId, jobArgs.toJSONString());
        } else {
            // replace with with getParameterValue
            boolean paramFound = false;
            for (int i = 0; i < commandArgs.size(); i++) {
                JSONObject jo = (JSONObject) commandArgs.get(i);
                Object oo = jo.get("outputname");
                if (oo != null) {
                    String strO = (String) oo;
                    if (strO.length() > 0) {
                        paramFound = true;
                        break;
                    }
                }
            }

            if (paramFound == false) {
                arg = new JSONObject();
                arg.put("outputname", jobId);
                commandArgs.add(arg);
            }

            String argStr = createPostBody(commandArgs);
            postJobRquest(jobId, argStr);
        }
    } catch (Exception ex) {
        ResourceErrorHandler.handleError("Error exporting data: " + ex.toString(), Status.INTERNAL_SERVER_ERROR,
                log);
    }
    JSONObject res = new JSONObject();
    res.put("jobid", jobId);
    return Response.ok(res.toJSONString(), MediaType.APPLICATION_JSON).build();
}

From source file:com.respam.comniq.models.MovieListParser.java

public void JSONWriter(JSONArray JSONarr) {
    try {//from   w w w  .  j a  va2  s  . com
        String path = System.getProperty("user.home") + File.separator + "comniq" + File.separator + "output";
        File userOutDir = new File(path);
        if (userOutDir.exists()) {
            System.out.println(userOutDir + " already exists");
        } else if (userOutDir.mkdirs()) {
            System.out.println(userOutDir + " was created");
        } else {
            System.out.println(userOutDir + " was not created");
        }

        FileWriter localList = new FileWriter(userOutDir + File.separator + "LocalList.json");
        localList.write(JSONarr.toJSONString());
        localList.flush();
        localList.close();
        System.out.println("Local Processing Complete");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.appzone.sim.services.handlers.MtLogCheckServiceHandler.java

@Override
protected String doProcess(HttpServletRequest request) {

    String sinceStr = request.getParameter(KEY_SINCE);
    logger.debug("request mt logs since: {}", sinceStr);

    long since = Long.parseLong(sinceStr);

    List<MtMessage> messages = mtMessageRepository.find(since);

    JSONArray list = new JSONArray();

    for (MtMessage mtMessage : messages) {

        String message = mtMessage.getMessage();
        String addresses = JSONValue.toJSONString(mtMessage.getAddresses());
        String receivedDate = "" + mtMessage.getReceivedDate();

        JSONObject json = new JSONObject();
        json.put(JSON_KEY_MESSAGE, message);
        json.put(JSON_KEY_ADDRESSES, JSONValue.parse(addresses));
        json.put(JSON_KEY_RECEIVED_DATE, receivedDate);

        list.add(json);/*from  w  w  w  . j  av a2 s .  com*/
    }

    logger.debug("returning response: {}", list);

    return list.toJSONString();
}