Example usage for org.json.simple JSONObject toJSONString

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

Introduction

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

Prototype

public String toJSONString() 

Source Link

Usage

From source file:org.opencastproject.adminui.endpoint.UsersSettingsEndpointTest.java

@Test
public void testGetUserSettingsInputsDefaultsExpectsDefaultLimitsAndOffsets()
        throws ParseException, IOException {
    InputStream stream = UsersSettingsEndpointTest.class.getResourceAsStream("/usersettings.json");
    InputStreamReader reader = new InputStreamReader(stream);
    JSONObject expected = (JSONObject) new JSONParser().parse(reader);
    JSONObject actual = (JSONObject) parser
            .parse(given().log().all().expect().statusCode(HttpStatus.SC_OK).contentType(ContentType.JSON)
                    .body("total", equalTo(10)).body("offset", equalTo(0)).body("limit", equalTo(100))
                    .body("results", hasSize(10)).when().get(rt.host("/settings.json")).asString());

    System.out.println(actual.toJSONString());
    compareIds("results", expected, actual);
}

From source file:com.mcapanel.plugin.PluginConnector.java

@SuppressWarnings("unchecked")
public long sendMethod(String method, String... params) {
    if (connected()) {
        String paramStr = StringUtils.join(params, ", ");

        JSONObject obj = new JSONObject();

        long time = System.currentTimeMillis();

        obj.put("type", "method");
        obj.put("time", time);
        obj.put("plugin", "McAdminPanel");
        obj.put("method", method);
        obj.put("params", paramStr);

        String cmd = "mcadminpanelplugincmd " + obj.toJSONString();

        OutputStream writer = server.getWriter();

        try {//  w ww . ja  va2 s  .  c  om
            writer.write((cmd + "\n").getBytes());
            writer.flush();
        } catch (IOException e) {
        }

        return time;
    }

    return -1;
}

From source file:mml.test.Editor.java

/**
 * Add a single option-group to the styles menu
 * @param select the selct element/*from  w w w  .  j a va2s .  c  o  m*/
 * @param dObj the dialect JSON object
 * @param name the name of the format collection in dObj
 * @param label the name of the optgroup to appear in menu
 */
private void addOptGroup(Element select, JSONObject dObj, String name, String label) {
    JSONArray items = (JSONArray) dObj.get(name);
    if (items != null) {
        Element group = new Element("optgroup");
        group.addAttribute("label", label);
        for (int i = 0; i < items.size(); i++) {
            JSONObject item = (JSONObject) items.get(i);
            Element option = new Element("option");
            item.put("type", name);
            String value = item.toJSONString();
            value = escape(value);
            option.addAttribute("value", value);
            String text = (String) item.get("prop");
            //System.out.println(text);
            option.addText(text);
            group.addChild(option);
        }
        select.addChild(group);
    }
}

From source file:hoot.services.nativeInterfaces.ProcessStreamInterface.java

@Override
public JSONObject exec(JSONObject cmd) throws NativeInterfaceException {
    log.debug("Executing command : " + cmd.toJSONString());
    String[] commandArr = null;//w ww. j  a  v a2s .  c om
    JSONObject ret = new JSONObject();
    CommandResult res = null;
    boolean addedToQ = false;
    try {
        String exec = cmd.get("exectype").toString();

        if (exec.equalsIgnoreCase("hoot")) {
            commandArr = createCmdArray(cmd);
        } else if (exec.equalsIgnoreCase("make")) {
            commandArr = createScriptCmdArray(cmd);
        } else if (exec.equalsIgnoreCase("bash")) {
            commandArr = createBashScriptCmdArray(cmd);
        } else {
            log.error("Failed to parse params: " + cmd.toJSONString());
            throw new NativeInterfaceException("Failed to parse params.",
                    NativeInterfaceException.HttpCode.BAD_RQUEST);
        }
        String commandStr = ArrayUtils.toString(commandArr);
        log.debug("Native call: " + commandStr);
        if (commandArr == null || commandArr.length == 0) {
            throw new NativeInterfaceException("Failed to parse params.",
                    NativeInterfaceException.HttpCode.BAD_RQUEST);
        }
        ICommandRunner cmdRunner = new CommandRunner();
        addedToQ = addToProcessQ(cmd, cmdRunner);

        log.debug("Start: " + new Date().getTime());
        res = cmdRunner.exec(commandArr);
        log.debug("End: " + new Date().getTime());
        if (res != null) {
            if (res.getExitStatus() == 0) {
                String stdOut = res.getStdout();
                log.debug("stdout: " + stdOut);
                ret.put("stdout", stdOut);

                String warnings = "";
                List<String> stdLines = IOUtils.readLines(new StringReader(stdOut));
                for (String ln : stdLines) {
                    if (ln.indexOf(" WARN ") > -1) {
                        warnings += ln;
                        warnings += "\n";
                    }

                    // we will cap the maximum length of warnings to 1k
                    if (warnings.length() > 1028) {
                        warnings += " more ..";
                        break;
                    }
                }
                if (warnings.length() > 0) {
                    System.out.println(stdOut);
                    ret.put("warnings", warnings);
                }
            } else {
                String err = res.getStderr();
                if (res.getExitStatus() == -9999) {
                    throw new Exception("User requested termination.");
                } else {
                    boolean doThrowException = true;
                    if (cmd.containsKey("throwerror")) {
                        doThrowException = Boolean.parseBoolean(cmd.get("throwerror").toString());
                    }
                    if (doThrowException) {
                        throw new Exception(err);
                    } else {
                        String stdOut = res.getStdout();
                        ret.put("stdout", stdOut);
                        ret.put("stderr", err);
                    }
                }
            }
        }
    } catch (Exception e) {
        if (res.getExitStatus() == -9999) {
            throw new NativeInterfaceException("Failed to execute." + e.getMessage(),
                    NativeInterfaceException.HttpCode.USER_CANCEL);
        } else {
            throw new NativeInterfaceException("Failed to execute." + e.getMessage(),
                    NativeInterfaceException.HttpCode.SERVER_ERROR);
        }

    } finally {
        if (addedToQ) {
            removeFromProcessQ(cmd);
        }
    }

    return ret;

}

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;//  w  w w.j ava 2 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.kyne.webby.rtk.web.WebServer.java

@SuppressWarnings("unchecked")
public void printJSON(final Map<String, Object> data, final Socket clientSocket) {
    try {// w  ww  . j  a  va 2  s  .com
        final DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
        out.writeBytes("HTTP/1.1 200 OK\r\n");
        out.writeBytes("Content-Type: application/json; charset=utf-8\r\n");
        out.writeBytes("Cache-Control: no-cache \r\n");
        out.writeBytes("Server: Bukkit Webby\r\n");
        out.writeBytes("Connection: Close\r\n\r\n");
        final JSONObject json = new JSONObject();
        json.putAll(data);
        out.writeBytes(json.toJSONString());
        out.flush();
        out.close();
    } catch (final SocketException e) {
        /* .. */
    } catch (final Exception e) {
        LogHelper.error(e.getMessage(), e);
    }
}

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;// ww  w  .  j  av  a 2 s  .  co  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.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:org.opencastproject.adminui.endpoint.UsersSettingsEndpointTest.java

@Test
public void testGetUserSettingsInputsNormalLimitsAndOffsetsExpectsDefaultLimitsAndOffsets()
        throws ParseException, IOException {
    InputStream stream = UsersSettingsEndpointTest.class.getResourceAsStream("/usersettings.json");
    InputStreamReader reader = new InputStreamReader(stream);
    JSONObject expected = (JSONObject) new JSONParser().parse(reader);

    JSONObject actual = (JSONObject) parser.parse(given().log().all().expect().statusCode(HttpStatus.SC_OK)
            .contentType(ContentType.JSON).body("total", equalTo(10)).body("offset", equalTo(0))
            .body("limit", equalTo(100)).body("results", hasSize(10)).when()
            .get(rt.host("/settings.json?limit=100&offset=0")).asString());

    System.out.println(actual.toJSONString());
    compareIds("results", expected, actual);
}

From source file:hoot.services.controllers.info.ReportsResourceTest.java

@Test
@Category(UnitTest.class)
public void testDeleteReport() throws Exception {
    String storePath = _rps._homeFolder + "/" + _rps._rptStorePath;
    File f = new File(storePath);
    File fWks = new File(storePath + "/123_test_del");
    if (fWks.exists()) {
        FileUtils.forceDelete(fWks);//w  w  w  .j  av a2s .  c  o m
    }
    FileUtils.forceMkdir(f);

    FileUtils.forceMkdir(fWks);
    String currTime = "" + System.currentTimeMillis();
    JSONObject metaData = new JSONObject();
    metaData.put("name", "Test Report1");
    metaData.put("description", "This is test report 1");
    metaData.put("created", currTime);
    metaData.put("reportpath", _rps._homeFolder + "/test-files/test_report1.pdf");
    File meta = new File(storePath + "/123_test_del/meta.data");
    FileUtils.write(meta, metaData.toJSONString());

    boolean isDel = _rps._deleteReport("123_test_del_not_exist");
    assertFalse(isDel);
    isDel = _rps._deleteReport("123_test_del");
    assertTrue(isDel);

}

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

private Map processProteinTab(ResourceRequest request) throws IOException {

    String pk = request.getParameter("pk");
    String keyword = request.getParameter("keyword");
    String experiment_id = request.getParameter("experiment_id");
    String facet = request.getParameter("facet");
    String sort = request.getParameter("sort");
    Map<String, String> key = new HashMap<>();

    String json = SessionHandler.getInstance().get(SessionHandler.PREFIX + pk);
    if (json == null) {
        key.put("facet", facet);
        key.put("keyword", keyword);
        SessionHandler.getInstance().set(SessionHandler.PREFIX + pk, jsonWriter.writeValueAsString(key));
    } else {/*from w w w . ja v a 2 s  . com*/
        key = jsonReader.readValue(SessionHandler.getInstance().get(SessionHandler.PREFIX + pk));
        key.put("facet", facet);
    }

    DataApiHandler dataApi = new DataApiHandler(request);
    String orig_keyword = key.get("keyword");

    if (experiment_id != null && !experiment_id.equals("")) {
        key.put("keyword", "experiment_id: (" + experiment_id.replaceAll(",", " OR ") + ")");
    } else if (experiment_id != null && experiment_id.equals("")) {

        List<String> experimentIds = new ArrayList<>();

        SolrQuery query = dataApi.buildSolrQuery(key, sort, facet, 0, -1, false);

        LOGGER.trace("[{}] {}", SolrCore.PROTEOMICS_EXPERIMENT.getSolrCoreName(), query);
        String apiResponse = dataApi.solrQuery(SolrCore.PROTEOMICS_EXPERIMENT, query);

        Map resp = jsonReader.readValue(apiResponse);
        Map respBody = (Map) resp.get("response");

        List<Map> sdl = (List<Map>) respBody.get("docs");
        for (Map doc : sdl) {
            experimentIds.add((String) doc.get("experiment_id"));
        }
        //         solr.setCurrentInstance(SolrCore.PROTEOMICS_EXPERIMENT);
        //         JSONObject object = null; //solr.getData(key, null, facet, 0, 10000, true, false, false);
        //
        //         JSONObject obj = (JSONObject) object.get("response");
        //         JSONArray obj1 = (JSONArray) obj.get("docs");
        //
        //         for (Object ob : obj1) {
        //            JSONObject doc = (JSONObject) ob;
        //            if (solrId.length() == 0) {
        //               solrId += doc.get("experiment_id").toString();
        //            }
        //            else {
        //               solrId += "," + doc.get("experiment_id").toString();
        //            }
        //         }

        key.put("keyword", "experiment_id: (" + StringUtils.join(experimentIds, " OR ") + ")");

        if (resp.containsKey("facet_counts")) {
            JSONObject facets = FacetHelper.formatFacetTree((Map) resp.get("facet_counts"));
            key.put("facets", facets.toJSONString());
            SessionHandler.getInstance().set(SessionHandler.PREFIX + pk, jsonWriter.writeValueAsString(key));
        }
        //         JSONObject facets = (JSONObject) object.get("facets");
        //         if (facets != null) {
        //            key.put("facets", facets.toString());
        //         }
    }

    String start_id = request.getParameter("start");
    String limit = request.getParameter("limit");
    int start = Integer.parseInt(start_id);
    int end = Integer.parseInt(limit);

    SolrQuery query = dataApi.buildSolrQuery(key, sort, facet, start, end, false);

    LOGGER.trace("[{}] {}", SolrCore.PROTEOMICS_PROTEIN.getSolrCoreName(), query);

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

    Map resp = jsonReader.readValue(apiResponse);
    Map respBody = (Map) resp.get("response");

    int numFound = (Integer) respBody.get("numFound");
    List<Map> sdl = (List<Map>) respBody.get("docs");

    key.put("keyword", orig_keyword);

    Map response = new HashMap();
    response.put("key", key);
    response.put("numFound", numFound);
    response.put("proteins", sdl);

    return response;
}