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:com.replaymod.sponge.recording.AbstractRecorder.java

/**
 * Converts the meta data supplied to a JSON string.
 * @param metaData The meta data/*  w w  w . j  a va2 s  .com*/
 * @return The JSON string
 */
@SuppressWarnings("unchecked")
private String toJson(ReplayMetaData metaData) {
    JSONObject data = new JSONObject();
    for (String key : metaData.keys()) {
        Object value = metaData.get(key).get();
        if (value instanceof Collection) {
            JSONArray array = new JSONArray();
            for (Object element : (Collection) value) {
                array.add(element == null ? null : element);
            }
            value = array;
        }
        data.put(key, value);
    }
    return data.toString();
}

From source file:br.com.painel.controller.LoginController.java

@RequestMapping("/recuperarSenha")
public @ResponseBody String recuperarSenha(Usuario usuario) throws EmailException {
    UsuarioDAO dao = new UsuarioDAO();
    JSONObject json = new JSONObject();

    if (dao.verificarEmail(usuario)) {
        Usuario usu;//from   w  ww. j  ava 2 s. com
        EnviarEmail email = new EnviarEmail();
        usu = dao.recuperarSenha(usuario);

        String mensagem = "Usuario: " + usu.getLogin().getUsername() + "\n Senha: " + usu.getLogin().getSenha()
                + "\n No responder esse email, em caso de dvidas entre em contato com o adminstrador.";

        email.enviarEmail(usuario.getEmail(), usu.getNome(), "Recuperao de senha", mensagem);

        json.put("retorno", "Sua senha foi enviada para seu email");
        return json.toString();

    }

    json.put("retorno", "Email nao cadastrado!");
    return json.toString();
}

From source file:de.fhg.fokus.odp.middleware.unittest.xTestCKANGateway.java

/**
 * Test the GetPackageSearchResults method.
 *///from ww  w  . j  a  v  a  2 s. co  m
@Test
public void testGetDataSetSearchResults() {
    // get the package details
    Object obj = ckanGW.getDataSetSearchResults("q=tho_test_243&all_fields=1");
    // testdescription
    // q=tho_test_243&all_fields=1
    // q=regionx

    JSONObject o = (JSONObject) obj;

    log.fine("############ SEARCH DATASET ############");
    log.fine("obj: " + o.toString());
    log.fine("obj: " + o.toJSONString().contains(DATASET_NAME));
    log.fine("obj: " + o.get("count"));

    assertEquals((Long) o.get("count") >= 1, true);
}

From source file:control.ParametrizacionServlets.EliminarActParamfisicoquimicos.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/* w w  w  .j a  va2s . 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 respError = new JSONObject(); // uno significa que no hay error
    try {
        int codigoAct = Integer.parseInt(request.getParameter("actividad"));
        int codigoParam = Integer.parseInt(request.getParameter("parametro"));

        //Obtenemos La informacion del manager
        ActParamFisicoquimicos manager = new ActParamFisicoquimicos();
        //Almacenamos el error que pueda resultar
        respError = manager.Eliminar(codigoAct, codigoParam);

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

    } catch (Exception ex) {
        respError.put("error", 0);
        response.setContentType("application/json");
        response.getWriter().write(respError.toString());
    }

}

From source file:cn.vlabs.umt.ui.servlet.OauthTokenServlet.java

private void dealOAuthSystemError(String redirectURI, OAuthSystemException e, HttpServletResponse response)
        throws IOException {
    try {//w  ww.j  a  v a  2 s  . co  m
        OAuthResponse resp = OAuthASResponse.errorResponse(400).setError("server_error")
                .setErrorDescription(e.getMessage()).location(redirectURI).buildJSONMessage();
        response.setStatus(resp.getResponseStatus());
        PrintWriter pw = response.getWriter();
        pw.print(resp.getBody());
        pw.flush();
        pw.close();
    } catch (OAuthSystemException ex) {
        LOG.error("redirectURI=" + redirectURI, ex);
        response.setStatus(400);
        JSONObject obj = new JSONObject();
        obj.put("error", "server_error");
        obj.put("error_description", ex.getMessage());
        PrintWriter pw = response.getWriter();
        pw.print(obj.toString());
        pw.flush();
        pw.close();
    }
    LOG.error("", e);
}

From source file:functionnality.LikerLineST2.java

public boolean createTable(String id) {
    CouchDBWebRequest couchDB = new CouchDBWebRequest();
    Document d;//from  ww  w  . j  a  v a  2s . c o  m
    //Crer le doc apres avoir vrifier qu'il existe bien dans Tisseo
    TisseoWebRequest tisseoR = new TisseoWebRequest("/linesList");
    tisseoR.addParameterGet("lineId", id);

    d = tisseoR.parseResultXML(tisseoR.requestWithGet());
    String shortName = "", name = "", type = "";

    couchDB.addPath("/id_ligne_" + id);
    if (d.getChildNodes().item(0).getChildNodes().getLength() < 4) {
        try {
            Node n = d.getChildNodes().item(0).getChildNodes().item(1);
            shortName = n.getAttributes().getNamedItem("shortName").getNodeValue();
            name = n.getAttributes().getNamedItem("name").getNodeValue();
            type = n.getChildNodes().item(1).getAttributes().getNamedItem("name").getNodeValue();
            JSONObject tableCreate = new JSONObject();
            tableCreate.put("ShortName",
                    new String(shortName.getBytes("ISO-8859-1"), Charset.forName("UTF-8")));
            tableCreate.put("Name", new String(name.getBytes("ISO-8859-1"), Charset.forName("UTF-8")));
            tableCreate.put("Type", new String(type.getBytes("ISO-8859-1"), Charset.forName("UTF-8")));
            tableCreate.put("like", 0);
            tableCreate.put("unlike", 0);
            tableCreate.put("Voted", new JSONArray());

            couchDB.requestWithPut(new String(tableCreate.toString().getBytes("UTF-8"), "UTF-8"));
        } catch (UnsupportedEncodingException ex) {
            return false;
        }

    } else {
        return false;
    }
    return true;
}

From source file:app.SQSMessage.java

public void sendmsg(Tweet t, String keyword) throws Exception {

    /*/*  w ww.j a v  a  2  s .  c  om*/
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * ().
     */
    credentials = new ProfileCredentialsProvider("default").getCredentials();
    AmazonSQS sqs = new AmazonSQSClient(credentials);
    Region usWest2 = Region.getRegion(Regions.US_EAST_1);
    sqs.setRegion(usWest2);

    System.out.println("===========================================");
    System.out.println("sending tweet to Queue");
    System.out.println("===========================================\n");

    try {

        // Send a message
        System.out.println("Sending a message to TweetQueue.\n");

        JSONObject obj = new JSONObject();

        obj.put("userId", t.getUserId() + "");
        obj.put("lng", t.getLongitude() + "");
        obj.put("lat", t.getLatitude() + "");
        obj.put("text", t.getText());
        // obj.put("time", t.getCreatedTime().toString());
        obj.put("kwd", keyword);

        //String TwtJson = "{\"userId\":\"" + t.getUserId() + "\",\"lng\":\"" + t.getLongitude() + "\",\"lat\":\"" + t.getLatitude() + "\",\"text\":\"" + JSONObject.escape(t.getText()) +  "\",\"time\":\"" + t.getCreatedTime() + "\",\"kwd\":\"" + keyword + "\"}";

        String TwtJson = obj.toString();

        System.out.println(TwtJson);
        sqs.sendMessage(new SendMessageRequest(q_url, TwtJson));

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to Amazon SQS, but was rejected with an error response for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with SQS, such as not "
                + "being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:at.uni_salzburg.cs.ckgroup.cscpp.mapper.RegData.java

@SuppressWarnings("unchecked")
@Override//from w  w w.j a v  a2s . co  m
public String toJSONString() {
    JSONObject obj = new JSONObject();
    obj.put("engUri", engineUri);
    obj.put("centralEngine", Boolean.valueOf(centralEngine));
    if (pilotConfig != null) {
        obj.put("pilotUri", pilotUri);
        obj.put("pilotName", pilotConfig.get("pilotName"));
    }
    if (wayPoints != null) {
        obj.put("waypoints", wayPoints);
    }
    if (sensors != null) {
        List<String> ss = new ArrayList<String>();
        ss.addAll(sensors);
        Collections.sort(ss);
        obj.put("sensors", ss);
    }
    return obj.toString();
}

From source file:CPD4414Assign3.ProductServlet.java

private String getResults(String query, String... params) {
    StringBuilder results = new StringBuilder();
    String result = "a";

    try (Connection conn = getConnection()) {
        PreparedStatement pstmt = conn.prepareStatement(query);

        for (int i = 1; i <= params.length; i++) {
            pstmt.setString(i, params[i - 1]);
        }/*  w w w . j a v a2s . c  om*/

        ResultSet rs = pstmt.executeQuery();
        JSONObject resultObj = new JSONObject();
        JSONArray productArr = new JSONArray();

        while (rs.next()) {
            Map productMap = new LinkedHashMap();
            productMap.put("productID", rs.getInt("productID"));
            productMap.put("name", rs.getString("name"));
            productMap.put("description", rs.getString("description"));
            productMap.put("quantity", rs.getInt("quantity"));
            productArr.add(productMap);
        }
        resultObj.put("product", productArr);
        result = resultObj.toString();

    } catch (SQLException ex) {
        Logger.getLogger(ProductServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
    return result;
}

From source file:fr.itldev.koya.alfservice.UserService.java

/**
 * Helper method to get the activity data for a user
 * //from www  . ja  v  a  2 s.  c o  m
 * @param userMail
 *            user mail
 * @return
 */
public String getActivityUserData(String userMail) throws KoyaServiceException {
    User user = getUser(userMail);
    String memberFN = "";
    String memberLN = "";

    memberFN = user.getFirstName();
    memberLN = user.getName();

    JSONObject activityData = new JSONObject();
    activityData.put("memberUserName", userMail);
    activityData.put("memberFirstName", memberFN);
    activityData.put("memberLastName", memberLN);
    activityData.put("title", (memberFN + " " + memberLN + " (" + userMail + ")").trim());
    return activityData.toString();
}