Example usage for org.json.simple JSONObject toString

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

Introduction

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

Prototype

@Override
    public String toString() 

Source Link

Usage

From source file:XBMCmote.java

/**
 *
 * @param title title of notification//from   w w w  .j  a v a 2  s  .c o m
 * @param message body of notification
 * @return command sent
 */
@Command
public String notify(String title, String message) {
    JSONObject request = XBMC.guiNotify;

    LinkedHashMap params = new LinkedHashMap();

    params.put("title", title);
    params.put("message", message);
    params.put("image", "info");

    request.put("params", params);

    String response = XBMC.sendCommand(request);

    return String.format("%s\n%s", request.toString(), response);
}

From source file:chat.com.client.ChatClient.java

private void jButtonSendActionPerformed(java.awt.event.ActionEvent evt) {

    String to = jTextFieldAddress.getText().trim();
    String message = jTextFieldMessage.getText();
    JSONObject jsonSendMess = new JSONObject();

    jsonSendMess.put("id", id);
    jsonSendMess.put("to", to);
    jsonSendMess.put("message", message);
    jsonSendMess.put("type", "chat");

    String json = jsonSendMess.toString();

    writer.println(json);/*from   ww  w  . j a v a  2 s .  c o m*/
    writer.flush();

    System.out.println(message);

    jTextFieldMessage.setText("");
    jTextAreaChat.append(message + " send: " + to + '\n');
}

From source file:Remote.java

public String sendCommand(JSONObject jsonBody) {
    InputStream response = null;/*from  ww w  .j  av  a 2 s .  c om*/
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    String data = "ERROR";

    try {
        try {
            HttpPost httpRequest = new HttpPost(path);
            StringEntity httpParams = new StringEntity(jsonBody.toString());
            httpParams.setContentType("application/json");
            httpRequest.setEntity(httpParams);
            response = httpClient.execute(httpRequest).getEntity().getContent();
            data = IOUtils.toString(response);
        } catch (Exception ex) {
            System.out.println(ex);
        } finally {
            httpClient.close();
        }
    } catch (IOException ex) {
        Logger.getLogger(Remote.class.getName()).log(Level.SEVERE, null, ex);
    }
    return data;
}

From source file:control.ProcesoVertimientosServlets.SeleccionarTasaRetributiva.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*w w  w. j  ava 2 s . c o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    JSONObject jsonObject1 = new JSONObject();
    try {
        int codigoProceso = Integer.parseInt(request.getParameter("codigoProceso"));
        ProgramarMonitoreo manager = new ProgramarMonitoreo();
        jsonObject1 = manager.getTasaRetributiva(codigoProceso);

        //Armamos la respuesta JSON y la enviamos
        response.setContentType("application/json");
        response.getWriter().write(jsonObject1.toString());

    } catch (SQLException ex) {

    }

}

From source file:clientserver.ServerThread.java

final void initClientData() {
    try {//www . j  av  a2  s .c  o  m
        OutputStreamWriter os = new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8);
        JSONObject jWriteobj = new JSONObject();
        jWriteobj.put("name1", "sp_on");
        jWriteobj.put("value1", 245);
        jWriteobj.put("name2", "sp_off");
        jWriteobj.put("value2", 45);
        jWriteobj.put("name3", "mc_on");
        jWriteobj.put("value3", 3455);
        jWriteobj.put("name4", "mc_off");
        jWriteobj.put("value4", 2045);
        os.write(jWriteobj.toString());
        os.flush();
    } catch (IOException e) {
        System.out.println("Write socket closing" + e.getMessage());
    }
}

From source file:com.avinashbehera.sabera.network.HttpClient.java

public static JSONObject SendHttpPostUsingUrlConnection(String url, JSONObject jsonObjSend) {

    URL sendUrl;/*from  ww w  .j a v a  2  s. c  o m*/
    try {
        sendUrl = new URL(url);
    } catch (MalformedURLException e) {
        Log.d(TAG, "SendHttpPostUsingUrlConnection malformed URL");
        return null;
    }

    HttpURLConnection conn = null;

    try {
        conn = (HttpURLConnection) sendUrl.openConnection();
        conn.setReadTimeout(15000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("POST");
        conn.setChunkedStreamingMode(1024);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.addRequestProperty("Content-length", jsonObjSend.toJSONString().length() + "");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        //writer.write(getPostDataStringfromJsonObject(jsonObjSend));
        Log.d(TAG, "jsonobjectSend = " + jsonObjSend.toString());
        //writer.write(jsonObjSend.toString());
        writer.write(String.valueOf(jsonObjSend));

        writer.flush();
        writer.close();
        os.close();

        int responseCode = conn.getResponseCode();
        Log.d(TAG, "responseCode = " + responseCode);

        if (responseCode == HttpsURLConnection.HTTP_OK) {

            Log.d(TAG, "responseCode = HTTP OK");

            InputStream instream = conn.getInputStream();

            String resultString = convertStreamToString(instream);
            instream.close();
            Log.d(TAG, "resultString = " + resultString);
            //resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"

            // Transform the String into a JSONObject
            JSONParser parser = new JSONParser();
            JSONObject jsonObjRecv = (JSONObject) parser.parse(resultString);
            // Raw DEBUG output of our received JSON object:
            Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>");

            return jsonObjRecv;

        }

    } catch (Exception e) {
        // More about HTTP exception handling in another tutorial.
        // For now we just print the stack trace.
        e.printStackTrace();
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return null;

}

From source file:kvadrere.pig.geo.TileGeometry.java

/**
   Breaks up @shape into tiles at resolution @maxZoom
        /*  ww w  .jav a 2s .c  om*/
   * @param quadkey
   * @param shape
   * @param properties
   * @param maxZoom
   *
   * @return DataBag of Tuples of geoJSON tiles at resolution @maxZoom
           
   */
public DataBag searchTile(String quadkey, Geometry shape, JSONObject properties, int maxZoom)
        throws IOException {
    DataBag polygonSlices = bagFactory.newDefaultBag();

    if (quadkey.length() == maxZoom) { // We are done, we have found a tile at our desired maxZoom that contains a portion of the initial polygon.
        if (shape.getArea() > 0.0) { // Skip empty punchout polygons (since our bounding box could easily have uncovered tiles)          
            JSONObject newProperties = setGeometry(shape, properties);
            ((Map) newProperties.get("properties")).put("quadkey", quadkey);

            Tuple newQuadKey = tupleFactory.newTuple(2);
            newQuadKey.set(0, quadkey);
            newQuadKey.set(1, newProperties.toString());
            polygonSlices.add(newQuadKey);
        }
    } else { //Move down to the next 4 child quadkeys 
        List<String> childKeys = QuadKeyUtils.childrenFor(quadkey);

        for (String childKey : childKeys) {
            Polygon tileBox = QuadKeyUtils.quadKeyToBox(childKey);
            Geometry polygonSlice = tileBox.intersection(shape);
            polygonSlice = (polygonSlice.getGeometryType().equals(GEOM_COLLEC) ? polygonSlice.getEnvelope()
                    : polygonSlice);

            for (Tuple tuple : searchTile(childKey, polygonSlice, properties, maxZoom)) {
                polygonSlices.add(tuple);
            }
        }
    }
    return polygonSlices;
}

From source file:hoot.services.controllers.ingest.BasemapResource.java

@GET
@Path("/enable")
@Produces(MediaType.TEXT_PLAIN)//from ww  w .  ja va  2  s  . c o  m
public Response enableBasemap(@QueryParam("NAME") final String bmName,
        @QueryParam("ENABLE") final String enable) {

    boolean doEnable = true;
    try {

        if (enable != null && enable.length() > 0) {
            doEnable = Boolean.parseBoolean(enable);
        }

        _toggleBaseMap(bmName, doEnable);
    } catch (Exception ex) {
        ResourceErrorHandler.handleError("Error enabling base map: " + bmName + " Error: " + ex.getMessage(),
                Status.INTERNAL_SERVER_ERROR, log);
    }

    JSONObject resp = new JSONObject();
    resp.put("name", bmName);
    resp.put("isenabled", doEnable);
    return Response.ok(resp.toString(), MediaType.TEXT_PLAIN).build();
}

From source file:control.UsuariosServlets.EliminarUsuarios.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//w w  w  .j  a  v  a 2s  .  c  om
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    //Obtenemos los paramtros enviados
    int codigo = Integer.parseInt(request.getParameter("codigo"));

    JSONObject respError = new JSONObject(); // uno significa que no hay error

    //Obtenemos La informacion del manager
    Usuarios manager = new Usuarios();
    try {
        //Almacenamos el error que pueda resultar
        respError = manager.Eliminar(codigo);
        //Armamos la respuesta JSON y la enviamos
        response.setContentType("application/json");
        response.getWriter().write(respError.toString());

    } catch (Exception ex) {
        respError.put("error", 0);
        //Armamos la respuesta JSON y la enviamos
        response.setContentType("application/json");
        response.getWriter().write(respError.toString());
    }

}

From source file:control.ProcesoVertimientosServlets.EliminarAnexoInformes.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*  w  ww.  ja va  2  s . c  o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    JSONObject resp = new JSONObject();
    try {
        int codigo = Integer.parseInt(request.getParameter("codigo"));
        int codigoProceso = Integer.parseInt(request.getParameter("codigoProceso"));

        InformeProcesoSeco manager = new InformeProcesoSeco();

        resp = manager.eliminarAnexos(codigo, codigoProceso);

        response.setContentType("application/json");
        response.getWriter().write(resp.toString());

    } catch (Exception ex) {
        resp.put("error", 0);
        response.getWriter().write(resp.toString());
    }

}