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.jitsi.videobridge.rest.HandlerImpl.java

/**
 * Gets a JSON representation of the <tt>VideobridgeStatistics</tt> of (the
 * associated) <tt>Videobridge</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/*  www .  j av a 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 doGetStatisticsJSON(Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    BundleContext bundleContext = getBundleContext();

    if (bundleContext != null) {
        StatsManager statsManager = ServiceUtils.getService(bundleContext, StatsManager.class);

        if (statsManager != null) {
            Iterator<Statistics> i = statsManager.getStatistics().iterator();
            Statistics statistics = null;

            if (i.hasNext())
                statistics = i.next();

            JSONObject statisticsJSONObject = JSONSerializer.serializeStatistics(statistics);
            Writer writer = response.getWriter();

            response.setStatus(HttpServletResponse.SC_OK);
            if (statisticsJSONObject == null)
                writer.write("null");
            else
                statisticsJSONObject.writeJSONString(writer);

            return;
        }
    }

    response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
}

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

/**
 * Modifies a <tt>Conference</tt> with ID <tt>target</tt> in (the
 * associated) <tt>Videobridge</tt>.
 *
 * @param target the ID of the <tt>Conference</tt> to modify in (the
 * associated) <tt>Videobridge</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 .  ja v  a  2  s  . c om*/
 * @param response the response either as the {@code Response} object or a
 * wrapper of that response
 * @throws IOException
 * @throws ServletException
 */
private void doPatchConferenceJSON(String target, Request baseRequest, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {
    Videobridge videobridge = getVideobridge();

    if (videobridge == null) {
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    } else {
        Conference conference = videobridge.getConference(target, null);

        if (conference == null) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else if (RESTUtil.isJSONContentType(request.getContentType())) {
            Object requestJSONObject = null;
            int status = 0;

            try {
                requestJSONObject = new JSONParser().parse(request.getReader());
                if ((requestJSONObject == null) || !(requestJSONObject instanceof JSONObject)) {
                    status = HttpServletResponse.SC_BAD_REQUEST;
                }
            } catch (ParseException pe) {
                status = HttpServletResponse.SC_BAD_REQUEST;
            }
            if (status == 0) {
                ColibriConferenceIQ requestConferenceIQ = JSONDeserializer
                        .deserializeConference((JSONObject) requestJSONObject);

                if ((requestConferenceIQ == null) || ((requestConferenceIQ.getID() != null)
                        && !requestConferenceIQ.getID().equals(conference.getID()))) {
                    status = HttpServletResponse.SC_BAD_REQUEST;
                } else {
                    ColibriConferenceIQ responseConferenceIQ = null;

                    try {
                        IQ responseIQ = videobridge.handleColibriConferenceIQ(requestConferenceIQ,
                                Videobridge.OPTION_ALLOW_NO_FOCUS);

                        if (responseIQ instanceof ColibriConferenceIQ) {
                            responseConferenceIQ = (ColibriConferenceIQ) responseIQ;
                        } else {
                            status = getHttpStatusCodeForResultIq(responseIQ);
                        }
                    } catch (Exception e) {
                        status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
                    }
                    if (status == 0 && responseConferenceIQ != null) {
                        JSONObject responseJSONObject = JSONSerializer
                                .serializeConference(responseConferenceIQ);

                        if (responseJSONObject == null)
                            responseJSONObject = new JSONObject();

                        response.setStatus(HttpServletResponse.SC_OK);
                        responseJSONObject.writeJSONString(response.getWriter());
                    }
                }
            }
            if (status != 0)
                response.setStatus(status);
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        }
    }
}

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

/**
 * Creates a new <tt>Conference</tt> in (the associated)
 * <tt>Videobridge</tt>./* w  w w  .  ja  v  a2 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
 */
private void doPostConferencesJSON(Request baseRequest, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {
    Videobridge videobridge = getVideobridge();

    if (videobridge == null) {
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    } else if (RESTUtil.isJSONContentType(request.getContentType())) {
        Object requestJSONObject = null;
        int status = 0;

        try {
            requestJSONObject = new JSONParser().parse(request.getReader());
            if ((requestJSONObject == null) || !(requestJSONObject instanceof JSONObject)) {
                status = HttpServletResponse.SC_BAD_REQUEST;
            }
        } catch (ParseException pe) {
            status = HttpServletResponse.SC_BAD_REQUEST;
        }
        if (status == 0) {
            ColibriConferenceIQ requestConferenceIQ = JSONDeserializer
                    .deserializeConference((JSONObject) requestJSONObject);

            if ((requestConferenceIQ == null) || (requestConferenceIQ.getID() != null)) {
                status = HttpServletResponse.SC_BAD_REQUEST;
            } else {
                ColibriConferenceIQ responseConferenceIQ = null;

                try {
                    IQ responseIQ = videobridge.handleColibriConferenceIQ(requestConferenceIQ,
                            Videobridge.OPTION_ALLOW_NO_FOCUS);

                    if (responseIQ instanceof ColibriConferenceIQ) {
                        responseConferenceIQ = (ColibriConferenceIQ) responseIQ;
                    } else {
                        status = getHttpStatusCodeForResultIq(responseIQ);
                    }
                } catch (Exception e) {
                    status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
                }
                if (status == 0 && responseConferenceIQ != null) {
                    JSONObject responseJSONObject = JSONSerializer.serializeConference(responseConferenceIQ);

                    if (responseJSONObject == null)
                        responseJSONObject = new JSONObject();

                    response.setStatus(HttpServletResponse.SC_OK);
                    responseJSONObject.writeJSONString(response.getWriter());
                }
            }
        }
        if (status != 0)
            response.setStatus(status);
    } else {
        response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
    }
}

From source file:org.megam.api.info.RequestInfo.java

public String json() throws APIInvokeException {
    try {// www  . ja v  a 2s .com
        JSONObject obj = new JSONObject();
        obj.put(REQTYPE, "build");
        obj.put(NODENAME, getNodeName());
        obj.put(APPDEFNSID, getId());
        obj.put(LCAPPLY, getRunTimeExec());
        obj.put(LCADDITIONAL, "");
        obj.put(LCWHEN, "");
        StringWriter out = new StringWriter();
        obj.writeJSONString(out);
        String jsonText = out.toString();
        System.out.print(jsonText);
        return jsonText;
    } catch (IOException ioe) {
        throw new APIInvokeException("", ioe);
    }
}

From source file:org.openme.openme.java

public static JSONObject openme_store_json_file(JSONObject i, String file_name) {
    /*/*ww w.j  ava 2 s.c  om*/
       Store json object in file
            
       Input:  i         - cJSON object
       file_name - name of the file to store json object
            
       Output: {
         cm_return       - return code = 0, if successful
         (cm_error)      - error text if return code > 0
       }
    */

    JSONObject r = new JSONObject();
    BufferedWriter fp = null;

    try {
        fp = new BufferedWriter(new FileWriter(file_name));
    } catch (IOException ex) {
        r.put("cm_return", new Long(1));
        r.put("cm_error", "can't open json file for writing (" + ex.getMessage() + ") ...");
        return r;
    }

    try {
        StringWriter out = new StringWriter();
        i.writeJSONString(out);
        fp.write(out.toString());
        fp.newLine();
    } catch (Exception ex) {
        try {
            fp.close();
        } catch (Exception ex1) {
            r.put("cm_return", new Long(1));
            r.put("cm_error", "can't close json file (" + ex1.getMessage() + ") ...");
            return r;
        }

        r.put("cm_return", new Long(1));
        r.put("cm_error", "can't write json file (" + ex.getMessage() + ") ...");
        return r;
    }

    try {
        fp.close();
    } catch (Exception ex) {
        r.put("cm_return", new Long(1));
        r.put("cm_error", "can't close json file (" + ex.getMessage() + ") ...");
        return r;
    }

    r.put("cm_return", new Long(0));
    return r;
}

From source file:org.openme.openme.java

public static JSONObject convert_cm_array_to_uri(JSONObject i) {
    /*//  w  w w  .ja va 2s. c  o  m
    Convert cM array to uri (convert various special parameters)
            
    Input:  {
      cm_array   - array to convert to uri
    }
            
    Output: {
      cm_return  - return code (check "access" function for full description)
      (cm_error) - error text  (check "access" function for full description)
      cm_string  - converted string
      cm_string1 - converted string (for urlopen)
    }
    */

    // Prepare return object
    JSONObject r = new JSONObject();

    JSONObject x = (JSONObject) i.get("cm_array");
    if (x == null) {
        r.put("cm_return", new Long(1));
        r.put("cm_error", "'cm_array' is not set in openme/convert_cm_array_to_uri");
        return r;
    }

    String s = "";
    String s1 = "";

    StringWriter out = new StringWriter();
    try {
        x.writeJSONString(out);
    } catch (Exception ex) {
        r.put("cm_return", new Long(1));
        r.put("cm_error", "can't output json (" + ex.getMessage() + ") ...");
        return r;
    }

    s = out.toString();

    s = s.replace("\"", "^22^");
    s = s.replace("#", "%23");

    s1 = s.replace(">", "%3E");
    s1 = s1.replace("<", "%3C");

    try {
        s = URLEncoder.encode(s, "UTF-8");
    } catch (Exception ex) {
        r.put("cm_return", new Long(1));
        r.put("cm_error", "can't encode string (" + ex.getMessage() + ") ...");
        return r;
    }

    r.put("cm_return", new Long(0));
    r.put("cm_string", s);
    r.put("cm_string1", s1);

    return r;
}

From source file:org.openme_ck.openme_ck.java

public static JSONObject openme_store_json_file(JSONObject i, String file_name) {
    /*/*from www  . j av a  2 s. c  om*/
       Store json object in file
            
       Input:  i         - cJSON object
       file_name - name of the file to store json object
            
       Output: {
         return       - return code = 0, if successful
         (error)      - error text if return code > 0
       }
    */

    JSONObject r = new JSONObject();
    BufferedWriter fp = null;

    try {
        fp = new BufferedWriter(new FileWriter(file_name));
    } catch (IOException ex) {
        r.put("return", new Long(1));
        r.put("error", "can't open json file for writing (" + ex.getMessage() + ") ...");
        return r;
    }

    try {
        StringWriter out = new StringWriter();
        i.writeJSONString(out);
        fp.write(out.toString());
        fp.newLine();
    } catch (Exception ex) {
        try {
            fp.close();
        } catch (Exception ex1) {
            r.put("return", new Long(1));
            r.put("error", "can't close json file (" + ex1.getMessage() + ") ...");
            return r;
        }

        r.put("return", new Long(1));
        r.put("error", "can't write json file (" + ex.getMessage() + ") ...");
        return r;
    }

    try {
        fp.close();
    } catch (Exception ex) {
        r.put("return", new Long(1));
        r.put("error", "can't close json file (" + ex.getMessage() + ") ...");
        return r;
    }

    r.put("return", new Long(0));
    return r;
}

From source file:org.openme_ck.openme_ck.java

public static JSONObject convert_array_to_uri(JSONObject i) {
    /*//from ww w. jav a2s .  c om
    Convert cM dict to uri (convert various special parameters)
            
    Input:  {
      dict   - dict to convert to uri
    }
            
    Output: {
      return  - return code (check "access" function for full description)
      (error) - error text  (check "access" function for full description)
      string  - converted string
    }
    */

    // Prepare return object
    JSONObject r = new JSONObject();

    JSONObject x = (JSONObject) i.get("dict");
    if (x == null) {
        r.put("return", new Long(1));
        r.put("error", "'array' is not set in openme/convert_array_to_uri");
        return r;
    }

    String s = "";
    String s1 = "";

    StringWriter out = new StringWriter();
    try {
        x.writeJSONString(out);
    } catch (Exception ex) {
        r.put("return", new Long(1));
        r.put("error", "can't output json (" + ex.getMessage() + ") ...");
        return r;
    }

    s = out.toString();

    try {
        s = URLEncoder.encode(s, "UTF-8");
    } catch (Exception ex) {
        r.put("return", new Long(1));
        r.put("error", "can't encode string (" + ex.getMessage() + ") ...");
        return r;
    }

    r.put("return", new Long(0));
    r.put("string", s);

    return r;
}

From source file:org.pentaho.osgi.i18n.webservice.ResourceBundleMessageBodyWriter.java

@Override
public void writeTo(ResourceBundle resourceBundle, Class<?> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
        throws IOException, WebApplicationException {
    if (MediaType.APPLICATION_JSON_TYPE.equals(mediaType)) {
        JSONObject resourceBundleJsonObject = new JSONObject();
        for (String key : Collections.list(resourceBundle.getKeys())) {
            resourceBundleJsonObject.put(key, resourceBundle.getString(key));
        }//w  ww. j a v a2s .c o  m
        OutputStreamWriter outputStreamWriter = null;
        try {
            outputStreamWriter = new OutputStreamWriter(entityStream);
            resourceBundleJsonObject.writeJSONString(outputStreamWriter);
        } finally {
            if (outputStreamWriter != null) {
                outputStreamWriter.flush();
            }
        }
    } else if (MediaType.APPLICATION_XML_TYPE.equals(mediaType)) {
        try {
            Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
            Node propertiesNode = document.createElement("properties");
            document.appendChild(propertiesNode);
            for (String key : Collections.list(resourceBundle.getKeys())) {
                Node propertyNode = document.createElement("property");
                propertiesNode.appendChild(propertyNode);

                Node keyNode = document.createElement("key");
                keyNode.setTextContent(key);
                propertyNode.appendChild(keyNode);

                Node valueNode = document.createElement("value");
                valueNode.setTextContent(resourceBundle.getString(key));
                propertyNode.appendChild(valueNode);
            }
            Result output = new StreamResult(entityStream);
            Source input = new DOMSource(document);
            try {
                Transformer transformer = TransformerFactory.newInstance().newTransformer();
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
                transformer.transform(input, output);
            } catch (TransformerException e) {
                throw new IOException(e);
            }
        } catch (ParserConfigurationException e) {
            throw new WebApplicationException(e);
        }
    }
}

From source file:org.projasource.dbimport.mojo.DataExportMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    try {//from   ww  w  .  ja  v  a 2  s . co m
        initDataSource();
        initStorage();
        if (extraConditions != null) {
            tableNames.removeAll(extraConditions.keySet());
        }
        final JSONObject export = new JSONObject();
        final SqlQueryExecutor exec = new SqlQueryExecutor(getManagedConnection());
        String select = "SELECT * FROM ";
        if (schema != null) {
            select += schema + ".";
        }
        if (extraConditions == null) {
            extraConditions = new HashMap<String, String>();
        }
        for (final String table : tableNames) {
            extraConditions.put(table, select + table);
        }
        for (final Entry<String, String> e : extraConditions.entrySet()) {
            final JSONArray t = new JSONArray();
            exec.execute(e.getValue(), null, new SqlQueryExecutor.RSCallback() {

                public String fetchResultSet(ResultSet rs) throws SQLException {
                    final List<String> fields = new ArrayList<String>();
                    for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
                        fields.add(rs.getMetaData().getColumnName(i));
                    }
                    while (rs.next()) {
                        final JSONObject row = new JSONObject();
                        for (final String field : fields) {
                            row.put(field, rs.getString(field));
                        }
                        t.add(row);
                    }
                    return null;
                }

            });
            export.put(e.getKey(), t);
        }
        final Writer out = new FileWriter(store);
        export.writeJSONString(out);
        out.flush();
        out.close();
    } catch (final Exception e) {
        e.printStackTrace();
        throw new MojoFailureException("Could not execute due to error", e);
    }
}