Example usage for org.json.simple JSONObject JSONObject

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

Introduction

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

Prototype

JSONObject

Source Link

Usage

From source file:co.edu.unal.arqdsoft.presentacion.JSON.java

/**
 * // w  ww. j a va2  s. c om
 * @param request
 * @return JSONObject con los parametros del request
 * @throws Exception 
 */
public static JSONObject toObject(HttpServletRequest request) throws Exception {
    if (request.getParameter("accion") != null) {//Servidor independiente
        JSONObject r = new JSONObject();
        r.put("accion", request.getParameter("accion"));
        r.put("datos", request.getParameter("datos"));
        return r;
    } else {//Servidor base netbeans
        InputStream is = request.getInputStream();
        byte[] charr = new byte[is.available()];
        is.read(charr);
        return (JSONObject) JSONValue.parse(new String(charr, "UTF-8"));
    }
}

From source file:myproject.MyServer.java

public static void List(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {//from   w  ww  . j av a2s.c  o  m
        String query = "SELECT * FROM student";
        String result = database.runQuery(query);
        response.getWriter().write(result);
    } catch (Exception ex) {
        JSONObject output = new JSONObject();
        output.put("error", "Connection failed: " + ex.getMessage());
        response.getWriter().write(JSONValue.toJSONString(output));
    }
}

From source file:gov.nih.nci.cma.web.ajax.RegHelper.java

public static String pReg(String ln, String fn, String em, String in, String ca, String ph, String de) {
    //look @ the captcha
    JSONObject jso = new JSONObject();
    String status = "pass";
    String msg = "";
    WebContext webContext = WebContextFactory.get();
    HttpSession session = webContext.getSession();

    String k = session.getAttribute(nl.captcha.servlet.Constants.SIMPLE_CAPCHA_SESSION_KEY) != null
            ? (String) session.getAttribute(nl.captcha.servlet.Constants.SIMPLE_CAPCHA_SESSION_KEY)
            : null;/*from   w w  w .j ava2  s  .  c  om*/

    if (k != null && k.equals(ca.trim())) {

        try {
            //need to clean the generalFeedback field, also put this in the props as a template
            MailProps mp = new MailProps();

            //make sure its only 1 email
            em = em.replace(",", "").replace(";", "");
            //send the mail to APP support
            /*
            String fdbk = fn + " " + ln + " is requesting an account for the CMA Application. \n\n";
            fdbk += "Their email is: " + em + " \n";
            fdbk += "Their institution is: " + in + " \n";
            fdbk += "\n\nThis is an automated email sent from the CMA Application.\n";
            */
            //String fdbk = System.getProperty("cma.register.template.support");
            Map propsMap = (Map) ConfigurationHolder.getFlatConfig();
            String fdbk = (String) propsMap.get("cma.register.template.support");
            fdbk = fdbk.replace("{last_name}", (ln != null) ? ln : "None");
            fdbk = fdbk.replace("{first_name}", (fn != null) ? fn : "None");
            fdbk = fdbk.replace("{email}", (em != null) ? em : "None");
            fdbk = fdbk.replace("{phone}", (ph != null) ? ph : "None");
            fdbk = fdbk.replace("{department}", (de != null) ? de : "None");
            fdbk = fdbk.replace("{institution}", (in != null) ? in : "None");

            mp.setBody(fdbk);
            //the fields below should be in a props file
            mp.setSmtp((String) propsMap.get("cma.feedback.mailSMPT"));
            mp.setSubject((String) propsMap.get("cma.register.mailSubject.support"));
            mp.setMailTo((String) propsMap.get("cma.register.mailTo.support"));
            mp.setMailFrom((String) propsMap.get("cma.feedback.mailFrom"));

            Mail.sendMail(mp);

            //send the mail to the user
            mp = new MailProps();
            fdbk = (String) propsMap.get("cma.register.template.user");
            fdbk = fdbk.replace("{last_name}", (ln != null) ? ln : "None");
            fdbk = fdbk.replace("{first_name}", (fn != null) ? fn : "None");
            /*
             fdbk = "Dear " + fn + " " + ln + ",\n Thanks for registering for access to the CMA Application.  You will receive your official account information via email shortly.  Please contact ncicb@pop.nci.nih.gov for further assistance.\n";
            fdbk += "\n\nSincerely,\n-The CMA Team";
            */
            mp.setBody(fdbk);
            mp.setSmtp((String) propsMap.get("cma.feedback.mailSMPT"));
            mp.setSubject((String) propsMap.get("cma.register.mailSubject.user"));
            mp.setMailTo(em.trim());
            mp.setMailFrom((String) propsMap.get("cma.feedback.mailFrom"));

            Mail.sendMail(mp);
        }

        catch (ValidationException e) {
            logger.error("mail did not send from regHelper");
            logger.error(e);
            status = "failed";
            msg = "SEND_FAILED";
        } catch (Exception e) {
            logger.error("mail did not send from regHelper");
            logger.error(e);
            status = "failed";
            msg = "SEND_FAILED_GENERIC";
        }
    } else {
        status = "fail";
        msg = "BAD_CAPTCHA";
    }

    jso.put("status", status);
    jso.put("msg", msg);

    if (status.equals("pass")) {
        // Uncomment the two lines below to enable login after registration (more steps are needed).
        // Should change the login parameters too
        //jso.put("un", "RBTuser");
        //jso.put("ps", "RBTpass");
    }

    return jso.toString();
}

From source file:at.ac.tuwien.dsg.quelle.sesConfigurationsRecommendationService.util.ConvertTOJSON.java

public static String convertTOJSON(List<Metric> metrics) {
    JSONArray children = new JSONArray();

    for (Metric m : metrics) {
        JSONObject metricJSON = new JSONObject();
        metricJSON.put("name", m.getName());
        metricJSON.put("unit", m.getMeasurementUnit());
        metricJSON.put("type", "" + m.getType());
        children.add(metricJSON);//from   www  . j a va2s. co  m
    }

    return children.toJSONString();
}

From source file:cs.rsa.ts14dist.common.CommandLanguage.java

@SuppressWarnings("unchecked")
/** Create a request object */
public static JSONObject createRequestObject(String user, String commandKey, String parameter) {
    JSONObject requestJson = new JSONObject();
    requestJson.put(Constants.USER_KEY, user);
    requestJson.put(Constants.COMMAND_KEY, commandKey);
    requestJson.put(Constants.PARAMETER_KEY, parameter);

    return requestJson;
}

From source file:model.Post_store.java

public static void add_post(String title, String content) {

    JSONObject obj = new JSONObject();
    obj.put("title", title);
    obj.put("content", content);

    JSONArray comments = new JSONArray();

    obj.put("comments", comments);

    JSONArray UA_comments = new JSONArray();

    obj.put("UA_comments", UA_comments);

    int lastid = getlastid();

    obj.put("id", lastid);

    try (FileWriter file = new FileWriter(root + "posts/" + lastid + ".json");) {
        file.write(obj.toJSONString());// w ww . j  a v a  2 s.c om
        file.flush();
        file.close();

    } catch (IOException e) {
        System.out.println(e);
    }

    lastid++;

    setlastid(lastid);

    //System.out.print(obj);

}

From source file:com.echonest.api.v4.Biography.java

public JSONObject toJSON() {
    JSONObject jo = new JSONObject();
    jo.put("site", this.getSite());
    jo.put("text", this.getText());
    jo.put("url", this.getURL());

    JSONObject li = new JSONObject();
    li.put("type", this.getLicenseType());
    li.put("attribution", this.getLicenseAttribution());

    jo.put("license", li);

    return jo;/* w  ww . j a  v  a 2  s .c o m*/
}

From source file:fi.hsl.parkandride.itest.JSONObjectBuilder.java

public JSONObjectBuilder() {
    jsonObject = new JSONObject();
}

From source file:javaphpmysql.JavaPHPMySQL.java

public static void sendPost() {
    //Creamos un objeto JSON
    JSONObject jsonObj = new JSONObject();
    //Aadimos el nombre, apellidos y email del usuario
    jsonObj.put("nombre", nombre);
    jsonObj.put("apellidos", apellidos);
    jsonObj.put("email", email);
    //Creamos una lista para almacenar el JSON
    List l = new LinkedList();
    l.addAll(Arrays.asList(jsonObj));
    //Generamos el String JSON
    String jsonString = JSONValue.toJSONString(l);
    System.out.println("JSON GENERADO:");
    System.out.println(jsonString);
    System.out.println("");

    try {/* w w w .j  av  a  2 s  .c o  m*/
        //Codificar el json a URL
        jsonString = URLEncoder.encode(jsonString, "UTF-8");
        //Generar la URL
        String url = SERVER_PATH + "listenPost.php";
        //Creamos un nuevo objeto URL con la url donde queremos enviar el JSON
        URL obj = new URL(url);
        //Creamos un objeto de conexin
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        //Aadimos la cabecera
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        //Creamos los parametros para enviar
        String urlParameters = "json=" + jsonString;
        // Enviamos los datos por POST
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();
        //Capturamos la respuesta del servidor
        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        //Mostramos la respuesta del servidor por consola
        System.out.println(response);
        //cerramos la conexin
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.conwet.silbops.connectors.comet.JSONUtils.java

@SuppressWarnings("unchecked")
public static String toJSONReply(String command, JSONObject parameters) {

    JSONObject json = new JSONObject();
    json.put("command", command);
    json.put("parameters", parameters);

    return json.toJSONString();
}