Example usage for org.json.simple JSONObject writeJSONString

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

Introduction

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

Prototype

public static void writeJSONString(Map<String, Object> map, Writer out) throws IOException 

Source Link

Usage

From source file:com.aipo.app.microblog.controller.TestController.java

@Override
protected Navigation run() throws Exception {
    response.setContentType("application/json;");
    response.setCharacterEncoding("utf-8");

    Map<String, Object> handle = new HashMap<String, Object>();
    if (MessageService.get().getMessageCount() == -1) {
        handle.put("status", "down");
    } else {//from   w ww . ja v  a 2 s . co m
        handle.put("status", "running");
    }

    JSONObject.writeJSONString(handle, response.getWriter());
    response.flushBuffer();
    return null;
}

From source file:com.cloudera.lib.wsrs.JSONMapProvider.java

@Override
public void writeTo(Map map, Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, Object> stringObjectMultivaluedMap, OutputStream outputStream)
        throws IOException, WebApplicationException {
    Writer writer = new OutputStreamWriter(outputStream);
    JSONObject.writeJSONString(map, writer);
    writer.write(ENTER);//from ww w  . j  av  a2s.co m
    writer.flush();
}

From source file:com.aipo.app.microblog.controller.JSONController.java

@Override
protected Navigation run() throws Exception {
    response.setContentType("application/json;");
    response.setCharacterEncoding("utf-8");

    Map<String, Object> handle = execute();
    if (handle.get(STATUS) == null) {
        handle.put(STATUS, 200);/* ww w. java2s .co m*/
    }

    JSONObject.writeJSONString(handle, response.getWriter());
    response.flushBuffer();
    return null;
}

From source file:com.aipo.app.microblog.controller.JSONController.java

@Override
protected Navigation handleError(Throwable error) throws Throwable {
    logger.log(Level.WARNING, error.getMessage(), error);
    Map<String, Object> map = Maps.newHashMap();
    String errorCode;/*from w ww  . ja  va2  s .c  om*/
    String errorMessage;
    int status = 500;
    boolean canRetry = false;
    if (error instanceof CapabilityDisabledException) {
        errorCode = "READONLY";
        errorMessage = "???";
    } else if (error instanceof DatastoreTimeoutException) {
        errorCode = "DSTIMEOUT";
        errorMessage = "??????";
        canRetry = true;
    } else if (error instanceof DatastoreFailureException) {
        errorCode = "DSFAILURE";
        errorMessage = "??????";
    } else if (error instanceof DeadlineExceededException) {
        errorCode = "DEE";
        errorMessage = "??????";
        canRetry = true;
    } else if (error instanceof EntityNotFoundRuntimeException) {
        status = 400;
        errorCode = "NOTFOUND";
        errorMessage = "????????";
        canRetry = true;
    } else {
        errorCode = "UNKNOWN";
        errorMessage = "??????";
    }
    map.put(STATUS, status);
    map.put(ERROR_CODE, errorCode);
    map.put(ERROR_MESSAGE, errorMessage);
    map.put(CAN_RETRY, canRetry);
    JSONObject.writeJSONString(map, response.getWriter());
    response.flushBuffer();
    return null;
}

From source file:com.cloudera.lib.service.instrumentation.TestInstrumentationService.java

@Test
@TestDir/*from   w w w .j  a  v  a2  s .  co m*/
@SuppressWarnings("unchecked")
public void service() throws Exception {
    String dir = getTestDir().getAbsolutePath();
    String services = StringUtils.toString(Arrays.asList(InstrumentationService.class.getName()), ",");
    XConfiguration conf = new XConfiguration();
    conf.set("server.services", services);
    Server server = new Server("server", dir, dir, dir, dir, conf);
    server.init();

    Instrumentation instrumentation = server.get(Instrumentation.class);
    Assert.assertNotNull(instrumentation);
    instrumentation.incr("g", "c", 1);
    instrumentation.incr("g", "c", 2);
    instrumentation.incr("g", "c1", 2);

    Instrumentation.Cron cron = instrumentation.createCron();
    cron.start();
    sleep(100);
    cron.stop();
    instrumentation.addCron("g", "t", cron);
    cron = instrumentation.createCron();
    cron.start();
    sleep(200);
    cron.stop();
    instrumentation.addCron("g", "t", cron);

    Instrumentation.Variable<String> var = new Instrumentation.Variable<String>() {
        @Override
        public String getValue() {
            return "foo";
        }
    };
    instrumentation.addVariable("g", "v", var);

    Instrumentation.Variable<Long> varToSample = new Instrumentation.Variable<Long>() {
        @Override
        public Long getValue() {
            return 1L;
        }
    };
    instrumentation.addSampler("g", "s", 10, varToSample);

    Map<String, ?> snapshot = instrumentation.getSnapshot();
    Assert.assertNotNull(snapshot.get("os-env"));
    Assert.assertNotNull(snapshot.get("sys-props"));
    Assert.assertNotNull(snapshot.get("jvm"));
    Assert.assertNotNull(snapshot.get("counters"));
    Assert.assertNotNull(snapshot.get("timers"));
    Assert.assertNotNull(snapshot.get("variables"));
    Assert.assertNotNull(snapshot.get("samplers"));
    Assert.assertNotNull(((Map<String, String>) snapshot.get("os-env")).get("PATH"));
    Assert.assertNotNull(((Map<String, String>) snapshot.get("sys-props")).get("java.version"));
    Assert.assertNotNull(((Map<String, ?>) snapshot.get("jvm")).get("free.memory"));
    Assert.assertNotNull(((Map<String, ?>) snapshot.get("jvm")).get("max.memory"));
    Assert.assertNotNull(((Map<String, ?>) snapshot.get("jvm")).get("total.memory"));
    Assert.assertNotNull(((Map<String, Map<String, Object>>) snapshot.get("counters")).get("g"));
    Assert.assertNotNull(((Map<String, Map<String, Object>>) snapshot.get("timers")).get("g"));
    Assert.assertNotNull(((Map<String, Map<String, Object>>) snapshot.get("variables")).get("g"));
    Assert.assertNotNull(((Map<String, Map<String, Object>>) snapshot.get("samplers")).get("g"));
    Assert.assertNotNull(((Map<String, Map<String, Object>>) snapshot.get("counters")).get("g").get("c"));
    Assert.assertNotNull(((Map<String, Map<String, Object>>) snapshot.get("counters")).get("g").get("c1"));
    Assert.assertNotNull(((Map<String, Map<String, Object>>) snapshot.get("timers")).get("g").get("t"));
    Assert.assertNotNull(((Map<String, Map<String, Object>>) snapshot.get("variables")).get("g").get("v"));
    Assert.assertNotNull(((Map<String, Map<String, Object>>) snapshot.get("samplers")).get("g").get("s"));

    StringWriter writer = new StringWriter();
    JSONObject.writeJSONString(snapshot, writer);
    writer.close();
    server.destroy();
}

From source file:org.ala.spatial.analysis.layers.SitesBySpeciesTabulated.java

/**
 * write decades tabulation.//from  w  w w  .  ja  va  2s.  c om
 * <p/>
 * Output filename is "decades.csv" and "decades.json".
 *
 * @param outputDirectory path to output directory.
 * @param decadeIdx       array of decades.
 * @param decMap          array of map of values to write.
 * @return
 */
private Map writeDecades(String outputDirectory, short[] decadeIdx, HashMap<Integer, Integer>[] decMap) {
    Map map = new HashMap();
    ArrayList array = new ArrayList();

    try {
        FileWriter fw = new FileWriter(outputDirectory + File.separator + "decades.csv");

        //identify column numbers
        TreeMap<Integer, Integer> tm = new TreeMap();
        for (int i = 0; i < decMap.length; i++) {
            tm.putAll(decMap[i]);
        }
        Integer[] cols = new Integer[tm.size()];
        tm.keySet().toArray(cols);

        ArrayList<Integer> c = new ArrayList<Integer>();
        for (int j = 0; j < cols.length; j++) {
            c.add(cols[j]);
            fw.write(",\"" + cols[j] + "\"");
        }

        //bioregion rows
        for (int i = 0; i < decMap.length; i++) {
            if (decMap[i].size() > 0) {
                ArrayList array2 = new ArrayList();
                int pos = java.util.Arrays.binarySearch(decadeIdx, (short) i);
                //seek to first
                while (pos > 0 && decadeIdx[pos - 1] == i) {
                    pos--;
                }
                String rowname = "no year recorded";
                if (i > 0) {
                    rowname = pos + " to " + (pos + 9);
                }
                fw.write("\n\"" + rowname + "\"");
                //count columns
                for (int j = 0; j < cols.length; j++) {
                    Integer v = decMap[i].get(cols[j]);
                    fw.write(",");
                    if (v != null) {
                        fw.write(v.toString());
                        array2.add(v.toString());
                    } else {
                        array2.add("");
                    }
                }
                Map m3 = new HashMap();
                m3.put("name", rowname);
                m3.put("row", array2);
                array.add(m3);
            }
        }

        Map m4 = new HashMap();
        m4.put("rows", array);
        m4.put("columns", c);
        map.put("decades", m4);

        fw.close();

        fw = new FileWriter(outputDirectory + File.separator + "decades.json");
        JSONObject.writeJSONString(map, fw);
        fw.close();

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

    return map;
}

From source file:org.ala.spatial.analysis.layers.SitesBySpeciesTabulated.java

/**
 * write decade counts tabulation.//w w  w.  j  a  v  a  2s  . c o m
 * <p/>
 * Output filename is "decadecounts.csv" and "decadecounts.json".
 *
 * @param outputDirectory path to output directory.
 * @param decadeIdx       array of decades.
 * @param decMap          array of map of values to write.
 * @return
 */
private Map writeDecadeCounts(String outputDirectory, HashMap<Integer, Integer>[] decCountMap) {
    Map map = new HashMap();
    ArrayList array = new ArrayList();

    try {
        FileWriter fw = new FileWriter(outputDirectory + File.separator + "decadecounts.csv");

        //identify column numbers
        TreeMap<Integer, Integer> tm = new TreeMap();
        for (int i = 1; i < decCountMap.length; i++) {
            tm.putAll(decCountMap[i]);
        }
        Integer[] cols = new Integer[tm.size()];
        tm.keySet().toArray(cols);

        ArrayList<Integer> c = new ArrayList<Integer>();
        for (int j = 0; j < cols.length; j++) {
            c.add(cols[j]);
            fw.write(",\"" + cols[j] + "\"");
        }

        //bioregion rows
        for (int i = 1; i < decCountMap.length; i++) {
            if (decCountMap[i].size() > 0) {
                ArrayList array2 = new ArrayList();
                String rowname = i + " Decades";
                fw.write("\n\"" + rowname + "\"");
                //count columns
                for (int j = 0; j < cols.length; j++) {
                    Integer v = decCountMap[i].get(cols[j]);
                    fw.write(",");
                    if (v != null) {
                        fw.write(v.toString());
                        array2.add(v.toString());
                    } else {
                        array2.add("");
                    }
                }
                Map m3 = new HashMap();
                m3.put("name", rowname);
                m3.put("row", array2);
                array.add(m3);
            }
        }

        Map m4 = new HashMap();
        m4.put("rows", array);
        m4.put("columns", c);
        map.put("decadecounts", m4);

        fw.close();

        fw = new FileWriter(outputDirectory + File.separator + "decadecounts.json");
        JSONObject.writeJSONString(map, fw);
        fw.close();

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

    return map;
}

From source file:org.ala.spatial.analysis.layers.SitesBySpeciesTabulated.java

/**
 * write bioregion tabulation./*www .  j  a  v  a 2 s  .com*/
 * <p/>
 * Output filename is name + ".csv" and name + ".json".
 *
 * @param name            output filename
 * @param outputDirectory directory for output.
 * @param columns         list of the bioregion names.
 * @param bioMap          data to write.
 * @return
 */
private Map writeBioregions(String name, String outputDirectory, String[] columns,
        HashMap<Integer, Integer>[] bioMap) {
    Map map = new HashMap();
    ArrayList array = new ArrayList();
    try {
        FileWriter fw = new FileWriter(outputDirectory + File.separator + name + ".csv");

        //identify column numbers
        TreeMap<Integer, Integer> tm = new TreeMap();
        for (int i = 0; i < columns.length; i++) {
            tm.putAll(bioMap[i]);
        }
        Integer[] cols = new Integer[tm.size()];
        tm.keySet().toArray(cols);

        ArrayList<Integer> c = new ArrayList<Integer>();
        for (int j = 0; j < cols.length; j++) {
            c.add(cols[j]);
            fw.write(",\"" + cols[j] + "\"");
        }

        //bioregion rows
        for (int i = 0; i < columns.length + 1; i++) {
            if (bioMap[i].size() > 0) {
                ArrayList array2 = new ArrayList();
                String rowname = "Undefined";
                if (i > 0) {
                    rowname = columns[i - 1];
                }
                fw.write("\n\"" + rowname + "\"");
                //count columns
                for (int j = 0; j < cols.length; j++) {
                    Integer v = bioMap[i].get(cols[j]);
                    fw.write(",");
                    if (v != null) {
                        fw.write(v.toString());
                        array2.add(v.toString());
                    } else {
                        array2.add("");
                    }
                }
                Map m3 = new HashMap();
                m3.put("name", rowname);
                m3.put("row", array2);
                array.add(m3);
            }
        }

        Map m4 = new HashMap();
        m4.put("rows", array);
        m4.put("columns", c);
        map.put(name, m4);

        fw.close();

        fw = new FileWriter(outputDirectory + File.separator + name + ".json");
        JSONObject.writeJSONString(map, fw);
        fw.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return map;
}

From source file:org.apache.hadoop.lib.service.instrumentation.TestInstrumentationService.java

@Test
@TestDir/* www  .  ja  v a  2 s .c o  m*/
@SuppressWarnings("unchecked")
public void service() throws Exception {
    String dir = TestDirHelper.getTestDir().getAbsolutePath();
    String services = StringUtils.join(",", Arrays.asList(InstrumentationService.class.getName()));
    Configuration conf = new Configuration(false);
    conf.set("server.services", services);
    Server server = new Server("server", dir, dir, dir, dir, conf);
    server.init();

    Instrumentation instrumentation = server.get(Instrumentation.class);
    assertNotNull(instrumentation);
    instrumentation.incr("g", "c", 1);
    instrumentation.incr("g", "c", 2);
    instrumentation.incr("g", "c1", 2);

    Instrumentation.Cron cron = instrumentation.createCron();
    cron.start();
    sleep(100);
    cron.stop();
    instrumentation.addCron("g", "t", cron);
    cron = instrumentation.createCron();
    cron.start();
    sleep(200);
    cron.stop();
    instrumentation.addCron("g", "t", cron);

    Instrumentation.Variable<String> var = new Instrumentation.Variable<String>() {
        @Override
        public String getValue() {
            return "foo";
        }
    };
    instrumentation.addVariable("g", "v", var);

    Instrumentation.Variable<Long> varToSample = new Instrumentation.Variable<Long>() {
        @Override
        public Long getValue() {
            return 1L;
        }
    };
    instrumentation.addSampler("g", "s", 10, varToSample);

    Map<String, ?> snapshot = instrumentation.getSnapshot();
    assertNotNull(snapshot.get("os-env"));
    assertNotNull(snapshot.get("sys-props"));
    assertNotNull(snapshot.get("jvm"));
    assertNotNull(snapshot.get("counters"));
    assertNotNull(snapshot.get("timers"));
    assertNotNull(snapshot.get("variables"));
    assertNotNull(snapshot.get("samplers"));
    assertNotNull(((Map<String, String>) snapshot.get("os-env")).get("PATH"));
    assertNotNull(((Map<String, String>) snapshot.get("sys-props")).get("java.version"));
    assertNotNull(((Map<String, ?>) snapshot.get("jvm")).get("free.memory"));
    assertNotNull(((Map<String, ?>) snapshot.get("jvm")).get("max.memory"));
    assertNotNull(((Map<String, ?>) snapshot.get("jvm")).get("total.memory"));
    assertNotNull(((Map<String, Map<String, Object>>) snapshot.get("counters")).get("g"));
    assertNotNull(((Map<String, Map<String, Object>>) snapshot.get("timers")).get("g"));
    assertNotNull(((Map<String, Map<String, Object>>) snapshot.get("variables")).get("g"));
    assertNotNull(((Map<String, Map<String, Object>>) snapshot.get("samplers")).get("g"));
    assertNotNull(((Map<String, Map<String, Object>>) snapshot.get("counters")).get("g").get("c"));
    assertNotNull(((Map<String, Map<String, Object>>) snapshot.get("counters")).get("g").get("c1"));
    assertNotNull(((Map<String, Map<String, Object>>) snapshot.get("timers")).get("g").get("t"));
    assertNotNull(((Map<String, Map<String, Object>>) snapshot.get("variables")).get("g").get("v"));
    assertNotNull(((Map<String, Map<String, Object>>) snapshot.get("samplers")).get("g").get("s"));

    StringWriter writer = new StringWriter();
    JSONObject.writeJSONString(snapshot, writer);
    writer.close();
    server.destroy();
}

From source file:org.apache.hadoop.lib.wsrs.JSONMapProvider.java

@Override
public void writeTo(Map map, Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, Object> stringObjectMultivaluedMap, OutputStream outputStream)
        throws IOException, WebApplicationException {
    Writer writer = new OutputStreamWriter(outputStream, Charsets.UTF_8);
    JSONObject.writeJSONString(map, writer);
    writer.write(ENTER);//  www  .j  av a2  s. co m
    writer.flush();
}