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 void writeJSONString(Writer out) throws IOException 

Source Link

Usage

From source file:org.alfresco.cacheserver.CacheServerIdentityImpl.java

private void persistData() {
    File dataFile = dataFile();/* w w w . j a va2  s.c  o  m*/

    try {
        Data data = new Data(id);
        JSONObject syncDataObject = toJSON(data);

        logger.debug("Persisting data " + data + " to " + dataFile.getAbsolutePath());

        Writer writer = new FileWriter(dataFile);
        try {
            syncDataObject.writeJSONString(writer);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    } catch (IOException e) {
        logger.warn("Unable to persist data to " + dataFile.getAbsolutePath());
    }
}

From source file:org.altlaw.hadoop.JsonReader.java

public void addSmidInJson(String src, String filename, SequenceFile.Writer output) throws Exception {
    InputStreamReader isr = new InputStreamReader(new FileInputStream(src));
    BufferedReader br = new BufferedReader(isr);
    String line;/* w w w  . j  ava  2  s.c om*/
    StringBuffer strings = new StringBuffer();
    while ((line = br.readLine()) != null) {
        JSONObject obj = (JSONObject) JSONValue.parse(line);
        obj.put("filename", filename);
        obj.put("video_id", this.getSMID(filename));
        StringWriter out = new StringWriter();
        obj.writeJSONString(out);
        String jsonText = out.toString();
        this.appendStringToOuput(filename, jsonText, output);
    }
    br.close();
    isr.close();
}

From source file:org.forgerock.openig.migrate.Main.java

void execute(OutputStream stream) throws Exception {

    // Pre-parse the original files with JSON-Simple parser (which is more lenient than Jackson's one)
    File source = new File(sources.get(0));
    JSONParser parser = new JSONParser();
    JSONObject object = (JSONObject) parser.parse(new FileReader(source));

    // Then serialize again the structure (should clean up the JSON)
    StringWriter writer = new StringWriter();
    object.writeJSONString(writer);

    // Load migration actions to apply in order
    List<Action> actions = loadActions();

    // Parse the cleaned-up content with Jackson this time
    JsonFactory factory = new JsonFactory();
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode node = (ObjectNode) mapper.readTree(writer.toString());

    // Apply migration actions
    for (Action action : actions) {
        node = action.migrate(node);//w ww.j a va  2 s .  c  o  m
    }

    // Serialize the migrated content on the given stream (with pretty printer)
    DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter();
    prettyPrinter.indentArraysWith(DefaultPrettyPrinter.Lf2SpacesIndenter.instance);
    mapper.writeTree(factory.createGenerator(stream).setPrettyPrinter(prettyPrinter), node);
}

From source file:org.gagravarr.mpxj.json.DojoGanttJSON.java

public static void toJSON(ProjectFile project, Writer out) throws IOException {
    JSONObject json = new JSONObject();

    // Boiler plate
    json.put("identifier", ID);

    // Start from the root
    JSONArray items = new JSONArray();
    handleTaskContainer(project, items);
    json.put("items", items);

    // Have it output as JSON
    json.writeJSONString(out);
}

From source file:org.geoserver.wps.gs.PagedUniqueProcessPPIO.java

@Override
public void encode(Object value, OutputStream os) throws Exception {
    PagedUniqueProcess.Results result = (PagedUniqueProcess.Results) value;
    JSONObject obj = new JSONObject();
    obj.put("featureTypeName", result.getFeatureTypeName());
    obj.put("fieldName", result.getFieldName());
    obj.put("size", result.getSize());
    obj.put("values", result.getValues());
    Writer writer = new OutputStreamWriter(os);
    obj.writeJSONString(writer);
    writer.flush();/*from   ww  w  . ja v  a2  s. co m*/
}

From source file:org.graylogalert.component.ConfigurationTest.java

public void changeConfigFile(String range, String[] queries) throws IOException {
    JSONObject jsonConfig = new JSONObject();
    List<String> queryList = new ArrayList<>();
    queryList.addAll(Arrays.asList(queries));
    try (Writer writer = new FileWriter("config.json", false)) {
        jsonConfig.put("queries", queryList);
        jsonConfig.put("range", "");
        jsonConfig.writeJSONString(writer);
        writer.flush();/*from   w w w . ja  v  a2 s .  c o m*/
        writer.close();
    }
}

From source file:org.jboss.arquillian.ce.adapter.AbstractOpenShiftAdapter.java

public <T> T jolokia(Class<T> expectedReturnType, String podName, Object input) throws Exception {
    if (input instanceof J4pRequest == false) {
        throw new IllegalArgumentException("Input must be a J4pRequest instance!");
    }/*from w ww  . j  a  v a2  s. c o m*/

    Proxy proxy = getProxy();

    String url = proxy.url(podName, "https", 8778, "/jolokia/", null);
    log.info(String.format("Jolokia URL: %s", url));

    J4pRequest request = (J4pRequest) input;
    JSONObject jsonObject = ReflectionUtils.invoke(J4pRequest.class, "toJson", new Class[0], request,
            new Object[0], JSONObject.class);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try (OutputStreamWriter out = new OutputStreamWriter(baos)) {
        jsonObject.writeJSONString(out);
        out.flush();
    }

    byte[] bytes = baos.toByteArray(); // copy
    baos.reset(); // re-use
    try (InputStream stream = proxy.post(url, "application/json", bytes)) {
        byte[] buffer = new byte[512];
        int numRead;
        while ((numRead = stream.read(buffer, 0, buffer.length)) >= 0) {
            baos.write(buffer, 0, numRead);
        }
    }
    String content = baos.toString();

    JSONParser parser = new JSONParser();
    JSONAware parseResult;
    try {
        parseResult = (JSONAware) parser.parse(content);
    } catch (ParseException e) {
        throw new IllegalArgumentException("Invalid Jolokia response: " + content);
    }
    if (parseResult instanceof JSONObject == false) {
        throw new IllegalStateException("Invalid JSON answer for a single request (expected a map but got a "
                + parseResult.getClass() + ")");
    }
    J4pResponse response = ReflectionUtils.invoke(J4pRequest.class, "createResponse",
            new Class[] { JSONObject.class }, request, new Object[] { parseResult }, J4pResponse.class);
    return expectedReturnType.cast(response.getValue());
}

From source file:org.jitsi.rest.AbstractJSONHandler.java

/**
 * Gets a JSON representation of the {@code Version} of the associated
 * server/service./*from w  w  w .j ava2 s . c  o m*/
 *
 * @param baseRequest the original unwrapped {@link Request} object
 * @param request the request either as the {@code Request} object or a
 * wrapper of that request
 * @param response the response either as the {@code Response} object or a
 * wrapper of that response
 * @throws IOException
 * @throws ServletException
 */
protected void doGetVersionJSON(Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    beginResponse(/*target*/ null, baseRequest, request, response);

    BundleContext bundleContext = getBundleContext();
    int status = HttpServletResponse.SC_SERVICE_UNAVAILABLE;

    if (bundleContext != null) {
        VersionService versionService = ServiceUtils.getService(bundleContext, VersionService.class);

        if (versionService != null) {
            org.jitsi.service.version.Version version = versionService.getCurrentVersion();
            JSONObject versionJSONObject = new JSONObject();

            versionJSONObject.put("name", version.getApplicationName());
            versionJSONObject.put("version", version.toString());
            versionJSONObject.put("os", System.getProperty("os.name"));

            Writer writer = response.getWriter();

            response.setStatus(status = HttpServletResponse.SC_OK);
            versionJSONObject.writeJSONString(writer);
        }
    }

    if (response.getStatus() != status)
        response.setStatus(status);

    endResponse(/*target*/ null, baseRequest, request, response);
}

From source file:org.jitsi.videobridge.rest.HandlerImpl.java

/**
 * Retrieves a JSON representation of a <tt>Conference</tt> with ID
 * <tt>target</tt> of (the associated) <tt>Videobridge</tt>.
 *
 * @param target the ID of the <tt>Conference</tt> of (the associated)
 * <tt>Videobridge</tt> to represent in JSON format
 * @param baseRequest the original unwrapped {@link Request} object
 * @param request the request either as the {@code Request} object or a
 * wrapper of that request//from   w  ww.ja va 2  s. c  o m
 * @param response the response either as the {@code Response} object or a
 * wrapper of that response
 * @throws IOException
 * @throws ServletException
 */
private void doGetConferenceJSON(String target, Request baseRequest, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {
    Videobridge videobridge = getVideobridge();

    if (videobridge == null) {
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    } else {
        // We allow requests for certain sub-resources of a Conference
        // though such as DominantSpeakerIdentification.
        int conferenceIDEndIndex = target.indexOf('/');
        String conferenceID = target;

        if ((conferenceIDEndIndex > 0) && (conferenceIDEndIndex < target.length() - 1)) {
            target = target.substring(conferenceIDEndIndex + 1);
            if (DOMINANT_SPEAKER_IDENTIFICATION.equals(target)) {
                conferenceID = conferenceID.substring(0, conferenceIDEndIndex);
            }
        }

        Conference conference = videobridge.getConference(conferenceID, null);

        if (conference == null) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else if (DOMINANT_SPEAKER_IDENTIFICATION.equals(target)) {
            doGetDominantSpeakerIdentificationJSON(conference, baseRequest, request, response);
        } else {
            ColibriConferenceIQ conferenceIQ = new ColibriConferenceIQ();

            conference.describeDeep(conferenceIQ);

            JSONObject conferenceJSONObject = JSONSerializer.serializeConference(conferenceIQ);

            if (conferenceJSONObject == null) {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            } else {
                response.setStatus(HttpServletResponse.SC_OK);
                conferenceJSONObject.writeJSONString(response.getWriter());
            }
        }
    }
}

From source file:org.jitsi.videobridge.rest.HandlerImpl.java

/**
 * Retrieves a JSON representation of the
 * <tt>DominantSpeakerIdentification</tt> of a specific <tt>Conference</tt>.
 *
 * @param baseRequest the original unwrapped {@link Request} object
 * @param request the request either as the {@code Request} object or a
 * wrapper of that request/*from w  w  w.  j a va2 s  .co  m*/
 * @param response the response either as the {@code Response} object or a
 * wrapper of that response
 * @throws IOException
 * @throws ServletException
 */
private void doGetDominantSpeakerIdentificationJSON(Conference conference, Request baseRequest,
        HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    ConferenceSpeechActivity conferenceSpeechActivity = conference.getSpeechActivity();

    if (conferenceSpeechActivity == null) {
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    } else {
        JSONObject jsonObject = conferenceSpeechActivity.doGetDominantSpeakerIdentificationJSON();

        if (jsonObject != null) {
            response.setStatus(HttpServletResponse.SC_OK);
            jsonObject.writeJSONString(response.getWriter());
        }
    }
}