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:mml.handler.get.MMLMetadataHandler.java

public void handle(HttpServletRequest request, HttpServletResponse response, String urn) throws MMLException {
    try {// w  w w. j  ava  2 s  . co m
        Connection conn = Connector.getConnection();
        docid = request.getParameter(Params.DOCID);
        if (docid == null || docid.length() == 0)
            docid = urn;
        JSONObject md = new JSONObject();
        boolean changed = false;
        String docId = docid;
        do {
            String jStr = conn.getMetadata(docId);
            if (jStr != null) {
                JSONObject jObj = (JSONObject) JSONValue.parse(jStr);
                Set<String> keys = jObj.keySet();
                Iterator<String> iter = keys.iterator();
                while (iter.hasNext()) {
                    String key = iter.next();
                    md.put(key, jObj.get(key));
                }
                changed = true;
            } else {
                String ctStr = conn.getFromDb(Database.CORTEX, docId);
                if (ctStr != null) {
                    JSONObject jObj = (JSONObject) JSONValue.parse(ctStr);
                    if (jObj.containsKey(JSONKeys.DESCRIPTION)) {
                        String desc = ((String) jObj.get(JSONKeys.DESCRIPTION)).replaceAll("%20", " ");
                        if (desc.startsWith("\""))
                            desc = desc.substring(1);
                        if (desc.endsWith("\""))
                            desc = desc.substring(0, desc.length() - 2);
                        desc = desc.replaceAll("\"\"", "\"");
                        md.put(JSONKeys.TITLE, desc);
                    } else if (!md.containsKey(JSONKeys.TITLE) && DocType.isLetter(docId)) {
                        int index = docId.lastIndexOf("/");
                        String shortId;
                        if (index != -1)
                            shortId = docId.substring(index + 1);
                        else
                            shortId = docId;
                        String[] parts = shortId.split("-");
                        StringBuilder sb = new StringBuilder();
                        String projid = Utils.getProjectId(docId);
                        if (parts.length >= 2) {
                            String from = Acronym.expand(projid, parts[parts.length - 2]);
                            String to = Acronym.expand(projid, parts[parts.length - 1]);
                            sb.append("Letter from " + from);
                            sb.append(" to ");
                            sb.append(to);
                            sb.append(",");
                        }
                        if (parts.length >= 3) {
                            for (int i = 0; i < 3; i++) {
                                if (DocType.isDay(parts[i])) {
                                    sb.append(" ");
                                    sb.append(trimZeros(parts[i]));
                                } else if (DocType.isMonth(parts[i])) {
                                    sb.append(" ");
                                    sb.append(Acronym.expand(projid, parts[i]));
                                } else if (DocType.isYear(parts[i])) {
                                    sb.append(" ");
                                    sb.append(parts[i]);
                                    // maybe only a year
                                    break;
                                }
                            }
                            md.put(JSONKeys.TITLE, sb.toString());
                        }
                    } else
                        System.out.println("No metadata found for " + docId);
                } else
                    System.out.println("No metadata found for " + docId);
                changed = false;
            }
            docId = Utils.chomp(docId);
        } while (changed);
        response.setContentType("application/json");
        response.setCharacterEncoding(encoding);
        String mdStr = md.toJSONString();
        response.getWriter().println(mdStr);
    } catch (Exception e) {
        throw new MMLException(e);
    }
}

From source file:backtype.storm.multilang.JsonSerializer.java

public Number connect(Map conf, TopologyContext context) throws IOException, NoOutputException {
    JSONObject setupInfo = new JSONObject();
    setupInfo.put("pidDir", context.getPIDDir());
    setupInfo.put("conf", conf);
    setupInfo.put("context", context);
    writeMessage(setupInfo);//from   w  w  w.  jav  a 2 s .  c  om

    Number pid = (Number) ((JSONObject) readMessage()).get("pid");
    return pid;
}

From source file:com.ibm.bluemix.hack.image.ImageEvaluator.java

@SuppressWarnings("unchecked")
public JSONObject analyzeImage(byte[] buf) throws IOException {

    JSONObject imageProcessingResults = new JSONObject();

    JSONObject creds = VcapServicesHelper.getCredentials("watson_vision_combined", null);

    String baseUrl = creds.get("url").toString();
    String apiKey = creds.get("api_key").toString();
    String detectFacesUrl = baseUrl + "/v3/detect_faces?api_key=" + apiKey + "&version=2016-05-20";
    String classifyUrl = baseUrl + "/v3/classify?api_key=" + apiKey + "&version=2016-05-20";

    OkHttpClient client = new OkHttpClient();

    RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
            .addFormDataPart("images_file", "sample.jpg", RequestBody.create(MediaType.parse("image/jpg"), buf))
            .build();//w  ww  . j a v a  2  s .c o m

    Request request = new Request.Builder().url(detectFacesUrl).post(requestBody).build();

    Response response = client.newCall(request).execute();
    String result = response.body().string();

    JSONParser jsonParser = new JSONParser();

    try {
        JSONObject results = (JSONObject) jsonParser.parse(result);
        // since we only process one image at a time, let's simplfy the json 
        // we send to the JSP.
        JSONArray images = (JSONArray) results.get("images");
        if (images != null && images.size() > 0) {
            JSONObject firstImage = (JSONObject) images.get(0);
            JSONArray faces = (JSONArray) firstImage.get("faces");
            imageProcessingResults.put("faces", faces);
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }

    // now request classification
    request = new Request.Builder().url(classifyUrl).post(requestBody).build();

    response = client.newCall(request).execute();
    result = response.body().string();
    try {
        JSONObject results = (JSONObject) jsonParser.parse(result);
        // since we only process one image at a time, let's simplfy the json 
        // we send to the JSP.
        JSONArray images = (JSONArray) results.get("images");
        if (images != null && images.size() > 0) {
            JSONObject firstImage = (JSONObject) images.get(0);
            JSONArray classifiers = (JSONArray) firstImage.get("classifiers");
            imageProcessingResults.put("classifiers", classifiers);
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return imageProcessingResults;
}

From source file:Employee.getAllCustomers.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w w w  .  j  a  v 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 {
    //json to pass back to our ajax request
    JSONArray jsonArray = new JSONArray();
    try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

        Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost;user=sa;password=nopw");

        Statement st = con.createStatement();

        String query = "SELECT * FROM [MatchesFromAbove].[dbo].[Customer] WHERE active=1";

        ResultSet rs = st.executeQuery(query);

        //loop through result set and create the json objects
        while (rs.next()) {
            JSONObject customerToAdd = new JSONObject();
            customerToAdd.put("ssn", rs.getString("SSN"));
            customerToAdd.put("ppp", rs.getString("PPP"));
            customerToAdd.put("rating", rs.getInt("Rating"));
            customerToAdd.put("lastActiveDate", rs.getTimestamp("LastActive").toString());
            //add the json object that we're passing into the json array
            jsonArray.add(customerToAdd);
        }
        //set the content type of our response
        response.setContentType("application/json");
        //printout prints it to our ajax call and it shows up there as data. you can use this data in the success function.
        PrintWriter printout = response.getWriter();
        printout.print(jsonArray);
        printout.flush();
        con.close();
    } catch (Exception e) {
        System.out.println(e.getMessage());
        return;
    }
}

From source file:com.modeln.batam.connector.wrapper.Pair.java

@SuppressWarnings("unchecked")
public String toJSONString() {
    JSONObject obj = new JSONObject();
    obj.put("name", name);
    obj.put("value", value);

    return obj.toJSONString();
}

From source file:modelo.ProcesoVertimientosManagers.InformacionTecnica.java

/**
 * //  w  w w.  ja v  a2 s .c  o m
 * Arma el JSON con la informacion tecnica.
 * 
 * @param codigoProceso
 * @return
 * @throws Exception 
 */
public JSONArray getInformacionTecnica(int codigoProceso) throws Exception {

    int cantidadDatos = hayDatos(codigoProceso);

    //Mangers necesarios y Delegates Necesarios
    PuntosVertimiento puntoVert = new PuntosVertimiento();
    ParamFisicoquimicos param = new ParamFisicoquimicos();

    //Creamos el contenedor principal del JSON
    JSONArray contenedorPrincipal = new JSONArray();

    //Obtenemos la informacion del punto de vertimiento.
    Object data[] = puntoVert.getPuntosParaInfoTecnica(codigoProceso);
    ResultSet rset1 = (ResultSet) data[0];

    //Array para guardar la informacion del punto
    JSONArray puntoArray = new JSONArray();
    int puntoMonitoreo = 0;

    //Guardamos la informacion del punto en el JSON
    while (rset1.next()) {

        JSONObject puntoObject = new JSONObject();

        puntoObject.put("codigo", rset1.getString("PUNTO_MONITOREO"));
        puntoMonitoreo = Integer.parseInt(rset1.getString("PUNTO_MONITOREO"));
        puntoObject.put("ubicacion", rset1.getString("UBICACION"));
        puntoObject.put("latitud", rset1.getString("LATITUD"));
        puntoObject.put("longitud", rset1.getString("LONGITUD"));
        puntoObject.put("ciiu", rset1.getString("CIIU"));
        puntoObject.put("fechaMonitoreo", rset1.getString("FECHA_MONITOREO_PUNTO"));
        puntoObject.put("descripcionCiiu", rset1.getString("DESCRIPCION_CIIU"));
        puntoObject.put("jordanadaProductivaDia", rset1.getString("JPRODDIAS"));
        puntoObject.put("jordanadaProductivaHoras", rset1.getString("JPRODHORAS"));
        puntoObject.put("jordanadaProductivaObsev", rset1.getString("JPRODOBV"));

        int ciiu = rset1.getInt("CIIU");

        //Guardamos las informacion de la jornada
        JSONArray arrayJornada = new JSONArray();
        SeleccionarInfoTecJornadas infoTecJornadas = new SeleccionarInfoTecJornadas();

        //Validamos si ya hay datos registrados en las jornadas y en los detalles de las jornadas.
        if (cantidadDatos > 0) {

            //Obtenemos La informacion de las jornadas y las guardamos en el JSON
            ResultSet rsetJornadas = infoTecJornadas.getJornadas(puntoMonitoreo);
            while (rsetJornadas.next()) {

                JSONObject objectJornada = new JSONObject();
                objectJornada.put("nombre", "Jornada " + rsetJornadas.getInt("JORNADA"));
                objectJornada.put("cargaDBO", rsetJornadas.getDouble("CARGA_DBO"));
                objectJornada.put("cargaSST", rsetJornadas.getDouble("CARGA_SST"));
                objectJornada.put("horaInicio", rsetJornadas.getString("HORA_INICIO"));
                objectJornada.put("horaFin", rsetJornadas.getString("HORA_FIN"));
                objectJornada.put("caudalJornada", rsetJornadas.getString("CAUDAL_JORNADA"));

                int jornada = rsetJornadas.getInt("JORNADA");

                //Obtenemos y guardamos la informacion de cada parametro
                Object data2[] = param.getParametrosParaInfoTecnica(puntoMonitoreo, jornada, ciiu);
                ResultSet rset2 = (ResultSet) data2[0];

                JSONArray arrayParametro = new JSONArray();
                while (rset2.next()) {

                    JSONObject objectParametro = new JSONObject();
                    objectParametro.put("parametro", rset2.getString("PARAMETRO"));
                    objectParametro.put("codigoParametro", rset2.getString("CODIGO_PARAMETRO"));
                    objectParametro.put("rangoInicial", rset2.getString("RANGO_INICIAL"));
                    objectParametro.put("rangoFinal", rset2.getString("RANGO_FINAL"));
                    objectParametro.put("valorInforme", rset2.getDouble("VALOR"));
                    objectParametro.put("cumple", rset2.getString("CUMPLE"));
                    objectParametro.put("observacion", rset2.getString("OBSERVACION"));
                    objectParametro.put("indicardorMenor", rset2.getString("MENOR"));

                    arrayParametro.add(objectParametro);
                }

                //Cerramos conexion de parametros
                SeleccionarPrmfisicoquimicos select2 = (SeleccionarPrmfisicoquimicos) data2[1];
                select2.desconectar();

                //Guardamos los parametros en la jornada.
                objectJornada.put("tabla", arrayParametro);

                //Guardamos la Jornada
                arrayJornada.add(objectJornada);
            }
            //Cerramos la conexion de jornadas

        } else if (cantidadDatos == 0) {

            //Guardamos la informacion de las jornadas
            for (int i = 1; i < 5; i++) {
                JSONObject objectJornada = new JSONObject();
                objectJornada.put("nombre", "Jornada " + i);
                objectJornada.put("cargaDBO", "");
                objectJornada.put("cargaSST", "");
                objectJornada.put("horaInicio", "");
                objectJornada.put("horaFin", "");
                objectJornada.put("caudalJornada", "");

                //Obtenemos y guardamos la informacion de cada parametro
                Object data2[] = param.getParametrosParaInfoTecnica(ciiu);
                ResultSet rset2 = (ResultSet) data2[0];

                JSONArray arrayParametro = new JSONArray();
                while (rset2.next()) {

                    JSONObject objectParametro = new JSONObject();
                    objectParametro.put("parametro", rset2.getString("PARAMETRO"));
                    objectParametro.put("codigoParametro", rset2.getString("CODIGO_PARAMETRO"));
                    objectParametro.put("rangoInicial", rset2.getString("RANGO_INICIAL"));
                    objectParametro.put("rangoFinal", rset2.getString("RANGO_FINAL"));
                    objectParametro.put("valorInforme", "");
                    objectParametro.put("cumple", "");
                    objectParametro.put("observacion", "");
                    objectParametro.put("indicardorMenor", "");

                    arrayParametro.add(objectParametro);
                }

                //Cerramos conexion de parametros
                SeleccionarPrmfisicoquimicos select2 = (SeleccionarPrmfisicoquimicos) data2[1];
                select2.desconectar();

                //Guardamos los parametros en la jornada.
                objectJornada.put("tabla", arrayParametro);

                //Guardamos la Jornada
                arrayJornada.add(objectJornada);
            }
        }

        //guardamos las jornadas en el punto
        puntoObject.put("jornadas", arrayJornada);
        puntoArray.add(puntoObject);

        infoTecJornadas.desconectar();
    }

    contenedorPrincipal.add(puntoArray);

    //Cerrar Conexion.
    SeleccionarPuntosVertimiento select = (SeleccionarPuntosVertimiento) data[1];
    select.desconectar();

    return contenedorPrincipal;
}

From source file:io.personium.client.ExtCellManager.java

/**
 * This method is used to create an ExtCell using an ExtCell object.
 * @param obj ExtCell object/*from  w ww . j  av a 2 s.co m*/
 * @return ExtCell object that is created
 * @throws DaoException Exception thrown
 */
@SuppressWarnings("unchecked")
public ExtCell create(ExtCell obj) throws DaoException {
    JSONObject body = new JSONObject();
    body.put("Url", obj.getUrl());
    JSONObject json = internalCreate(body);
    obj.initialize(this.accessor, json);
    return obj;
}

From source file:biomine.bmvis2.pipeline.ClearOperation.java

public JSONObject toJSON() {
    return new JSONObject();
}

From source file:com.fujitsu.dc.engine.rs.StatusResource.java

/**
 * GET???./*from w w w.j  a  va  2s  . com*/
 * @return JAS-RS Response
 */
@SuppressWarnings("unchecked")
@GET
@Produces("application/json")
public Response get() {
    StringBuilder sb = new StringBuilder();

    // 
    Properties props = DcEngineConfig.getProperties();
    JSONObject responseJson = new JSONObject();
    JSONObject propertiesJson = new JSONObject();
    for (String key : props.stringPropertyNames()) {
        String value = props.getProperty(key);
        propertiesJson.put(key, value);
    }
    responseJson.put("properties", propertiesJson);

    sb.append(responseJson.toJSONString());
    return Response.status(HttpStatus.SC_OK).entity(sb.toString()).build();
}

From source file:Json.JsonWrite.java

public void jsonCreate(String patchName) {
    JSONObject obj = new JSONObject();
    obj.put("patch", this.patch);
    obj.put("page", this.page);
    obj.put("eddWay", this.eddWay);
    obj.put("proffName", this.proffName);
    obj.put("yearStart", this.YStart);
    obj.put("yearEnd", this.YEnd);
    obj.put("eddName", this.EddName);

    File file = new File(patchName);

    try {/*from  w w  w . java  2s.  c  o  m*/
        //?,  ?   ??  ? 
        if (!file.exists()) {
            file.createNewFile();
        }

        //PrintWriter ? ? ?  
        PrintWriter out = new PrintWriter(file.getAbsoluteFile());

        try {
            //? ?  
            out.print(obj);
        } finally {
            //?     
            //   ??
            out.close();
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}