Example usage for org.json.simple JSONArray toString

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

Introduction

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

Prototype

@Override
    public String toString() 

Source Link

Usage

From source file:gwap.rest.LocationService.java

/**
 * A topic denotes the set of pictues that can be used in a game such as "Munich" or "Baroque" 
 * /*from  w w  w. j  a  v  a 2s  .  c o  m*/
 * @param userId
 * @return
 */
@GET
@Path("/topics") // $HOST/seam/resource/rest/location/topics
@Produces(MediaType.APPLICATION_JSON)
@SuppressWarnings("unchecked")
public Response getTopics(@QueryParam("userid") String userId) {

    if (userId == null)
        return Response.status(Response.Status.NOT_ACCEPTABLE).build();

    Query query = entityManager.createNamedQuery("virtualTaggingType.all");
    ArrayList<VirtualTaggingType> virtualTaggingTypes = (ArrayList<VirtualTaggingType>) query.getResultList();

    JSONArray jsonArray = new JSONArray();
    for (VirtualTaggingType virtualTaggingType : virtualTaggingTypes) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("text", virtualTaggingType.getName());
        jsonObject.put("value", virtualTaggingType.getId());
        jsonObject.put("available", true); //TODO: Calculate availability 
        jsonArray.add(jsonObject);
    }

    log.info("UserId: #0", userId);
    return Response.ok(jsonArray.toString(), MediaType.APPLICATION_JSON).build();
}

From source file:com.jgoetsch.eventtrader.source.ApeStreamingMsgSource.java

public void receiveMsgs(HttpClient client) {
    if (executeRequest(client, createCommandRequest("CONNECT", getRequestParameters()), new MsgParser() {
        public boolean parseContent(InputStream input, long length, String contentType, MsgHandler handler) {
            JSONArray responseJson = (JSONArray) JSONValue
                    .parse(new BufferedReader(new InputStreamReader(input)));
            for (Object obj : responseJson) {
                if (((JSONObject) obj).get("raw").equals("LOGIN")) {
                    JSONObject data = (JSONObject) ((JSONObject) obj).get("data");
                    sessid = (String) data.get("sessid");
                }/*  w  ww .  jav  a2  s .  c o  m*/
            }
            if (sessid != null)
                return true;
            else {
                log.error("Could not find sessid in server response: " + responseJson.toString());
                return false;
            }
        }
    })) {
        log.info("Connected to " + getUrl() + " with session id " + sessid);
        if (initialCommands != null) {
            for (Command command : initialCommands) {
                log.info("Issuing command " + command.getCmd() + " " + command.getParams());
                if (!executeRequest(client, createCommandRequest(command.getCmd(), command.getParams()),
                        getMsgParser()))
                    break;
            }
        }
        super.receiveMsgs(client);
    }
}

From source file:gwap.rest.User.java

@GET
@Path("/highscore")
public Response getHighscore() {
    Query query = entityManager.createNamedQuery("highscore.all");
    query.setParameter("gametype", getGameType());
    query.setMaxResults(10);//from w  w  w.  ja  v a 2  s  . com
    List<Highscore> highscoreList = query.getResultList();

    JSONArray highscoreListJSON = new JSONArray();
    for (int i = 0; i < highscoreList.size(); i++) {
        Highscore highscore = highscoreList.get(i);
        JSONObject highscoreJSON = new JSONObject();
        highscoreJSON.put("rank", i + 1);
        Person person = entityManager.find(Person.class, highscore.getPersonId());
        highscoreJSON.put("name", person.getExternalUsername());
        highscoreJSON.put("score", highscore.getScore());
        highscoreListJSON.add(highscoreJSON);
    }

    return Response.ok(highscoreListJSON.toString(), MediaType.APPLICATION_JSON).build();
}

From source file:control.ParametrizacionServlets.EliminarAsociacionContrato.java

private void eliminarContratosAsociados(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    JSONArray respError = new JSONArray();

    try {/*from w  ww .j  a v  a 2  s. c  o m*/
        //Obtenemos los paramtros enviados
        int codigo = Integer.parseInt(request.getParameter("codigo"));

        // uno significa que no hay error

        //Obtenemos La informacion del manager
        AsociacionContratos manager = new AsociacionContratos();

        //Almacenamos el error que pueda resultar
        respError = manager.EliminarContratoAsociado(codigo);

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

        for (Object jsonObject : respError) {

            response.getWriter().write(respError.toString());

        }

    } catch (Exception e) {

        JSONObject error = new JSONObject();
        error.put("error", 0);
        respError.add(error);
        //Armamos la respuesta JSON y la enviamos
        response.setContentType("application/json");

        for (Object jsonObject : respError) {

            response.getWriter().write(respError.toString());

        }
    }
}

From source file:eclserver.threads.EmergencyNotifyPush.java

private String getJsonString(String machineName, String confirmURL) {

    JSONObject m1 = new JSONObject();
    m1.clear();//from   w  w  w  .  j  a  va  2  s.  co m
    JSONArray list1 = new JSONArray();

    try {
        m1.put("details", enPanel.getNotifyDetails());
        m1.put("acknowledgeurl", confirmURL + "?MyMessage=EmergencyNotificationAcknowledged");

        list1.add(m1);

    } catch (Exception ex) {
        // ex.printStackTrace();
    }

    String jsonString = "{\"Source\":[{\"machinename\":\"" + machineName + "\"}],";
    jsonString += "\"Confirmation\":[{\"url\":\"" + confirmURL + "\"}],";
    jsonString += "\"EmergencyCall\":" + list1.toString() + "}";

    System.out.println("Call JSON: " + jsonString);

    return jsonString;

}

From source file:hoot.services.controllers.job.ExportJobResource.java

/**
 * <NAME>Export Service Get WFS List</NAME>
 * <DESCRIPTION>//from  w w w  . j ava2  s. c om
 *    Lists all wfs resources
 * </DESCRIPTION>
 * <PARAMETERS>
 * </PARAMETERS>
 * <OUTPUT>
 *    List of wfs resources
 * </OUTPUT>
 * <EXAMPLE>
 *    <URL>http://localhost:8080/hoot-services/job/export/wfs/resources</URL>
 *    <REQUEST_TYPE>GET</REQUEST_TYPE>
 *    <INPUT>
 *   </INPUT>
 * <OUTPUT>[{"id":"ex_eed379c0b9f7469d80ab32c71550883b"}]</OUTPUT>
 * </EXAMPLE>
 * @return
 */
@GET
@Path("/wfs/resources")
@Produces(MediaType.TEXT_PLAIN)
public Response getWfsResources() {
    JSONArray srvList = new JSONArray();
    try {
        WfsManager wfsMan = new WfsManager();
        List<String> list = wfsMan.getAllWfsServices();

        for (int i = 0; i < list.size(); i++) {
            String wfsResource = list.get(i);
            JSONObject o = new JSONObject();
            o.put("id", wfsResource);
            srvList.add(o);
        }

    } catch (Exception ex) {
        ResourceErrorHandler.handleError("Error retrieving WFS resource list: " + ex.toString(),
                Status.INTERNAL_SERVER_ERROR, log);
    }

    return Response.ok(srvList.toString(), MediaType.TEXT_PLAIN).build();
}

From source file:com.plancake.api.client.PlancakeApiClient.java

/**
  * @param long fromTimestamp - to return only the lists created or edited after this timestamp (GMT)
  * @param long toTimestamp - to return only the lists created or edited till this timestamp (GMT)
 * @return List<Long> - set of list ids
 *//*  w  w  w .  j ava2  s . c om*/
public String[] whatHasChanged(long fromTimestamp, long toTimestamp)
        throws PlancakeApiException, UnsupportedEncodingException, NoSuchAlgorithmException, URISyntaxException,
        MalformedURLException, IOException {
    Map<String, String> params = new HashMap<String, String>();
    String methodName = "whatHasChanged";

    params.put("from_ts", Long.toString(fromTimestamp));
    params.put("to_ts", Long.toString(toTimestamp));

    JSONObject jsonResponse = this.sendRequest(params, methodName);

    JSONArray jsonArrayChanged = (JSONArray) jsonResponse.get("changed");

    // the fromJsonArrayToStringArray method has a bug
    String[] temp = Utils.fromJsonArrayToStringArray(jsonArrayChanged.toString());

    for (int j = 0; j < temp.length; j++) {
        temp[j] = temp[j].replace("\"", "");
    }

    return temp;
}

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

@GET
@Path("/getlist")
@Produces(MediaType.TEXT_PLAIN)/*from   ww w.ja  v a  2s  .c  om*/
public Response getBasemapList() {
    JSONArray retList = new JSONArray();
    Map<String, JSONObject> sortedScripts = new TreeMap<String, JSONObject>();
    JSONArray filesList = new JSONArray();

    try {
        filesList = _getBasemapList();
    } catch (Exception ex) {
        ResourceErrorHandler.handleError("Error getting base map list: " + ex.getMessage(),
                Status.INTERNAL_SERVER_ERROR, log);
    }

    // sort the list
    for (Object o : filesList) {
        JSONObject cO = (JSONObject) o;
        String sName = cO.get("name").toString();
        sortedScripts.put(sName.toUpperCase(), cO);
    }

    retList.addAll(sortedScripts.values());

    return Response.ok(retList.toString(), MediaType.TEXT_PLAIN).build();
}

From source file:com.plancake.api.client.PlancakeApiClient.java

/**
  * @param long fromTimestamp - to return only the lists created or edited after this timestamp (GMT)
  * @param long toTimestamp - to return only the lists created or edited till this timestamp (GMT)
 * @return List<Long> - set of list ids
 *///from   ww w. j a v a2s  .  c o m
public ArrayList<Long> getDeletedTasks(long fromTimestamp, long toTimestamp)
        throws PlancakeApiException, UnsupportedEncodingException, NoSuchAlgorithmException, URISyntaxException,
        MalformedURLException, IOException {
    Map<String, String> params = new HashMap<String, String>();
    String methodName = "getDeletedTasks";

    params.put("from_ts", Long.toString(fromTimestamp));
    params.put("to_ts", Long.toString(toTimestamp));

    JSONObject jsonResponse = this.sendRequest(params, methodName);

    JSONArray jsonArrayTaskIds = (JSONArray) jsonResponse.get("task_ids");

    ArrayList<Long> taskIds = new ArrayList<Long>();

    String[] commaSeparatedTaskIds = Utils.fromJsonArrayToStringArray(jsonArrayTaskIds.toString());

    long tempItemId = 0;

    for (int i = 0; i < commaSeparatedTaskIds.length; i++) {
        try {
            tempItemId = Long.parseLong(commaSeparatedTaskIds[i]);
            taskIds.add(tempItemId);
        } catch (NumberFormatException e) {
        }
    }

    return taskIds;
}

From source file:eclserver.threads.EmergencyCallPush.java

private String getJsonString(String machineName, String confirmURL) {

    JSONObject m1 = new JSONObject();
    m1.clear();// w ww  .j av  a 2 s .c  om
    JSONArray list1 = new JSONArray();

    try {
        m1.put("milliseconds", ecPanel.getCallDateTime());
        m1.put("phonenumber", ecPanel.getCallBridge());
        m1.put("details", ecPanel.getCallDescription());
        m1.put("accepturl", confirmURL + "?MyMessage=EmergencyCallAccepted");
        m1.put("declineurl", confirmURL + "?MyMessage=EmergencyCallDeclined");

        list1.add(m1);

    } catch (Exception ex) {
        System.out.println("EXCEPTION GETTING JSON STRING: " + ex.getMessage());

    }

    String jsonString = "{\"Source\":[{\"machinename\":\"" + machineName + "\"}],";
    jsonString += "\"Confirmation\":[{\"url\":\"" + confirmURL + "\"}],";
    jsonString += "\"EmergencyCall\":" + list1.toString() + "}";

    // System.out.println("Call JSON STRING: " + jsonString);

    return jsonString;

}