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:net.duckling.ddl.web.api.APIBundleItemsController.java

@SuppressWarnings("unchecked")
@RequestMapping//from   w w w .  j a  v a2 s .c  o  m
public void service(HttpServletRequest request, HttpServletResponse response) {
    JSONObject object = new JSONObject();
    Site site = findSite(request);
    List<Resource> elementList = null;

    String bidStr = request.getParameter("bid");
    if (StringUtils.isNotEmpty(bidStr)) {// bundle
        int tid = site.getId();
        int bid = Integer.parseInt(bidStr);
        elementList = folderPathService.getChildren(tid, bid);
    }

    JSONArray array = JsonUtil.getJSONArrayFromResourceList(elementList);
    object.put("records", array);
    JsonUtil.writeJSONObject(response, object);
}

From source file:com.saludtec.web.DatosClinicaWeb.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        String servicio = request.getRequestURI().replace("/Adminio/datosClinica/", "");
        switch (servicio) {
        case "gethospital":
            traerClinica(request).writeJSONString(out);
            break;

        case "savehospital":
            guardarClinica(request).writeJSONString(out);
            break;

        case "updatehospital":
            editarClinica(request).writeJSONString(out);
            break;

        default://w w  w  .ja va2  s  .  c o m
            obj = new JSONObject();
            obj.put("error", "404 - El servicio " + servicio + " no existe");
            obj.writeJSONString(out);
            break;

        }

    } catch (NonexistentEntityException ex) {
        Logger.getLogger(DatosClinicaWeb.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.conwet.silbops.msg.MessageTest.java

@Test
public void testMessageDelegatePayloadSerialization() {

    Message instance = new MockMessage();
    instance = spy(instance);/*from w  ww. j a va 2 s .co  m*/

    JSONObject jsonObject = instance.toJSON();
    verify(instance).getPayloadAsJSON();

    assertThat(jsonObject.get("type")).isEqualTo("NONE");
    assertThat(jsonObject.get("payload")).isEqualTo(new JSONObject());
}

From source file:edu.usc.polar.OpenNLP.java

public static void ApacheOpenNLP(String doc, String args[]) {
    try {/*from   w w w. java  2s.  c  o  m*/
        String text;
        AutoDetectParser parser = new AutoDetectParser();
        BodyContentHandler handler = new BodyContentHandler();
        Metadata metadata = new Metadata();

        InputStream stream = new FileInputStream(doc);

        //   System.out.println(stream.toString());
        parser.parse(stream, handler, metadata);
        // return handler.toString();
        text = handler.toString();
        String metaValue = metadata.toString();
        System.out.println("Desc:: " + metadata.get("description"));

        String[] example = new String[1];
        example[0] = text;
        String name = doc.replace("C:\\Users\\Snehal\\Documents\\TREC-Data\\Data", "polar.usc.edu");
        Map<String, Set<String>> list = tikaOpenNLP(text);
        System.out.println(combineSets(list));
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("DOI", name);
        jsonObj.put("metadata", metaValue.replaceAll("\\s\\s+|\n|\t", " "));
        JSONArray tempArray = new JSONArray();
        JSONObject tempObj = new JSONObject();
        for (Map.Entry<String, Set<String>> entry : list.entrySet()) {
            System.out.println("\"" + entry.getKey() + "/" + ":\"" + entry.getValue() + "\"");
            tempObj.put(entry.getKey(), entry.getValue());
            //          String jsonOut="{ DOI:"+name+"  ,"
            //                + ""+item.first() + "\": \"" + text.substring(item.second(), item.third()).replaceAll("\\s\\s+|\n|\t"," ")+"\""
            //                + "\"metadata\":\""+metaValue+"\""
            //                + "}";
            // System.out.println(jsonOut);
            //     tempObj.put(item.first(),text.substring(item.second(), item.third()).replaceAll("\\s\\s+|\n|\t"," "));
        }
        tempArray.add(tempObj);
        jsonObj.put("NER", tempArray);
        jsonArray.add(jsonObj);

        // System.out.println("---");

    } catch (Exception e) {
        System.out.println("ERROR : OpenNLP" + "|File Name"
                + doc.replaceAll("C:\\Users\\Snehal\\Documents\\TREC-Data", "") + " direct" + e.toString());
    }
}

From source file:ch.simas.jtoggl.Tag.java

public JSONObject toJSONObject() {
    JSONObject object = new JSONObject();
    if (id != null) {
        object.put("id", id);
    }//  www.j a v a 2s .  co m
    if (name != null) {
        object.put("name", name);
    }

    if (workspace != null) {
        object.put("workspace", this.workspace.toJSONObject());
    }

    return object;
}

From source file:ch.zhaw.icclab.tnova.expressionsolver.KPI.java

@GET
@Produces(MediaType.APPLICATION_JSON)// ww w. j  av  a  2s.  c  o  m
public String showKPI() {
    KPI.api_calls += 1; //tracking the current call
    JSONObject obj = new JSONObject();
    obj.put("src", "t-nova expression evaluation service");
    obj.put("msg", "kpi parameters data");

    obj.put("api-calls-total", api_calls);
    obj.put("api-calls-failed", api_calls_failed);
    obj.put("expressions-evaluated", expressions_evaluated);
    obj.put("expressions-under-evaluation", expressions_under_evaluation);
    Date date = new Date(lastknownunixtime);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
    sdf.setTimeZone(TimeZone.getTimeZone("GMT+1"));
    String formattedDate = sdf.format(date);
    obj.put("data-since", formattedDate);

    KPI.api_calls_success += 1;
    obj.put("api-calls-success", api_calls_success);
    //lastknownunixtime = System.currentTimeMillis();
    initialize();
    logger.info("URI:/kpi Method:GET Request procesed. The KPI parameters have been reset.");
    return obj.toJSONString();
}

From source file:com.mycompany.rent.controllers.MapController.java

@RequestMapping(value = "/data", method = RequestMethod.GET)
public File homePage(Map model) throws IOException {

    List<ForRent> allRentals = new ArrayList();

    allRentals = forRentDao.allRentals();

    JSONObject responseDetailsJson = new JSONObject();
    JSONArray array = new JSONArray();
    for (ForRent f : allRentals) {
        array.add(f.getLat());//from  w  w  w.j  a  v  a2 s .  c om
        array.add(f.getLon());
    }

    responseDetailsJson.put("data", (Object) array);//Here you can see the data in json format

    File file = new File("/home/brennan/_repos/rent/src/main/webapp/json/data.json");

    String path = file.getPath();

    try {

        // Writing to a file  
        file.createNewFile();
        FileWriter fileWriter = new FileWriter(file);

        fileWriter.write(responseDetailsJson.toJSONString());
        fileWriter.flush();
        fileWriter.close();

    } catch (IOException e) {

    }

    FileReader fr = new FileReader(file);

    return file;
}

From source file:control.ParametrizacionServlets.InsertarLaboratorios.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request// w w w.ja  v  a2  s .  co 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 salida = new JSONObject();
    try {

        String nombre = request.getParameter("nombre");
        String direccion = request.getParameter("direccion");
        String telefono = request.getParameter("telefono1");
        String telefono2 = request.getParameter("telefono2");
        String correo = request.getParameter("correo");
        String resolucion = request.getParameter("resolucion");
        String vigencia = request.getParameter("vigencia");
        String contactos = request.getParameter("contactos");
        String paramAcreditados = request.getParameter("paramAcreditados");

        Laboratorios manager = new Laboratorios();
        manager.insertar(nombre, contactos, direccion, telefono, telefono2, correo, resolucion, vigencia);

        AcreditacionParametros managerAcreditacion = new AcreditacionParametros();

        int codigoLaboratorio = manager.getCodigoLaboratorio();
        // la informacion se converte en unJSONArray

        Object obj = JSONValue.parse(paramAcreditados);
        JSONArray jsonArray = new JSONArray();
        jsonArray = (JSONArray) obj;

        //Recorremos el JSONArray y obtenemos la informacion.
        for (int i = 0; i < jsonArray.size(); i++) {

            JSONObject jsonObject = (JSONObject) jsonArray.get(i);
            int codParametro = Integer.parseInt((String) jsonObject.get("codigoParam"));

            managerAcreditacion.insertar(codParametro, codigoLaboratorio);

        }

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

}

From source file:identify.SendMessage.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//w w w . j  av  a 2 s.  c  o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, ParseException {
    String sender = request.getParameter("sender");
    String receiver = request.getParameter("receiver");
    String message = request.getParameter("body");
    int index = SaveToken.storage.findUsername(receiver);
    System.out.println(index);
    String tokenTo = SaveToken.storage.getData().get(index).getToken();
    JSONObject obj = new JSONObject();
    obj.put("sender", sender);
    obj.put("receiver", receiver);
    obj.put("body", message);
    JSONObject arrayObj = new JSONObject();
    arrayObj.put("to", tokenTo);
    arrayObj.put("data", obj);
    System.out.println(arrayObj.toString());
    String USER_AGENT = "Mozilla/5.0";
    String authKey = "key=AIzaSyBPldzkpB5YtLm3N8cYbdoweqtn5Dk3IfQ";
    String contentType = "application/json";
    String url = "https://fcm.googleapis.com/fcm/send";
    URL connection = new URL(url);
    HttpURLConnection con = (HttpURLConnection) connection.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
    con.setRequestProperty("Content-Type", contentType);
    con.setRequestProperty("Authorization", authKey);

    String urlParameters = arrayObj.toString();
    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuilder resp = new StringBuilder();
    while ((inputLine = in.readLine()) != null) {
        resp.append(inputLine);
    }
    in.close();
    String acrHeaders = request.getHeader("Access-Control-Request-Headers");
    String acrMethod = request.getHeader("Access-Control-Request-Method");
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Headers", acrHeaders);
    response.setHeader("Access-Control-Allow-Methods", acrMethod);
    response.setContentType("application/json:charset=UTF-8");
    response.getWriter().write(resp.toString());
}

From source file:com.lifetime.util.TimeOffUtil.java

public static HttpEntity getTimeoffRequestEntity(int page, int pagesize) {
    if ((page <= 0) || (pagesize <= 0)) {
        return null;
    }//w ww  . j a va2  s.  com

    JSONObject jsonObject = new JSONObject();

    jsonObject.put("page", String.valueOf(page));
    jsonObject.put("pagesize", String.valueOf(pagesize));

    JSONArray columnUris = new JSONArray();

    columnUris.add("urn:replicon:time-off-list-column:time-off");
    columnUris.add("urn:replicon:time-off-list-column:time-off-type");
    columnUris.add("urn:replicon:time-off-list-column:department-of-time-off-owner");

    jsonObject.put("columnUris", columnUris);

    JSONArray sort = new JSONArray();

    JSONObject sortObject = new JSONObject();

    sortObject.put("columnUri", "urn:replicon:time-off-list-column:time-off");
    sortObject.put("isAscending", "false");

    sort.add(sortObject);

    JSONObject filter = new JSONObject();

    JSONObject leftExpression = new JSONObject();

    leftExpression.put("filterDefinitionUri", "urn:replicon:time-off-list-filter:time-off-type");

    filter.put("leftExpression", leftExpression);

    filter.put("operatorUri", "urn:replicon:filter-operator:equal");

    JSONObject value = new JSONObject();

    value.put("string", "us-pto");

    JSONObject rightExpression = new JSONObject();

    rightExpression.put("value", value);

    filter.put("rightExpression", rightExpression);

    jsonObject.put("filterExpression", filter);

    HttpEntity entity = null;

    String jsonString = jsonObject.toJSONString();

    try {
        entity = new StringEntity(jsonString);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    return entity;
}