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:cn.vlabs.umt.ui.servlet.AuthorizationCodeServlet.java

public void writeJSONResponse(HttpServletResponse response, JSONObject obj) {
    PrintWriter writer = null;/*from  w  w w.j a  v a 2 s  .  c  o m*/
    try {
        //IE???text/html?
        response.setContentType("text/html");
        writer = response.getWriter();
        writer.write(obj.toString());
    } catch (IOException e) {
        LOG.error("JSONHelper write json object IOException:" + e.getMessage());
        LOG.debug(e.getStackTrace());
    } finally {
        if (writer != null) {
            writer.flush();
            writer.close();
        }
    }
}

From source file:com.aes.controller.EmpireController.java

public String getQuestionDetails(HttpServletRequest request) {
    List<String> questions = new ArrayList();
    for (String q : request.getParameterValues("questions")) {
        questions.add(q);//from   www.jav  a  2s  . com
    }

    List<String> answers = new ArrayList();
    for (String a : request.getParameterValues("answers")) {
        answers.add(a);
    }

    List<List> choices = new ArrayList();
    for (int x = 1; x < (questions.size()) + 1; x++) {
        List<String> ch = new ArrayList();
        for (String c : request.getParameterValues("choice" + x)) {
            ch.add(c);
        }
        choices.add(ch);
    }

    JSONObject json = new JSONObject();
    for (int x = 1; x < (questions.size()) + 1; x++) {
        JSONObject g = new JSONObject();
        g.put("Question", questions.get(x - 1));
        g.put("Answer", answers.get(x - 1));
        g.put("Choices", choices.get(x - 1));
        json.put(x - 1, g);
    }
    return json.toString();
}

From source file:com.nubits.nubot.RPC.NuRPCClient.java

private JSONObject invokeRPC(String id, String method, List params) {
    DefaultHttpClient httpclient = new DefaultHttpClient();

    JSONObject json = new JSONObject();
    json.put("id", id);
    json.put("method", method);
    if (null != params) {
        JSONArray array = new JSONArray();
        array.addAll(params);//from   w w w.  ja  v  a2  s. co m
        json.put("params", params);
    }
    JSONObject responseJsonObj = null;
    try {
        httpclient.getCredentialsProvider().setCredentials(new AuthScope(this.ip, this.port),
                new UsernamePasswordCredentials(this.rpcUsername, this.rpcPassword));
        StringEntity myEntity = new StringEntity(json.toJSONString());
        if (Global.options.verbose) {
            LOG.info("RPC : " + json.toString());
        }
        HttpPost httppost = new HttpPost("http://" + this.ip + ":" + this.port);
        httppost.setEntity(myEntity);

        if (Global.options.verbose) {
            LOG.info("RPC executing request :" + httppost.getRequestLine());
        }
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();

        if (Global.options.verbose) {
            LOG.info("RPC----------------------------------------");
            LOG.info("" + response.getStatusLine());

            if (entity != null) {
                LOG.info("RPC : Response content length: " + entity.getContentLength());
            }
        }
        JSONParser parser = new JSONParser();
        String entityString = EntityUtils.toString(entity);
        LOG.debug("Entity = " + entityString);
        /* TODO In case of wrong username/pass the response would be the following .Consider parsing it.
        Entity = <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                "http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
                <HTML>
                <HEAD>
                <TITLE>Error</TITLE>
                <META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>
                </HEAD>
                <BODY><H1>401 Unauthorized.</H1></BODY>
                </HTML>
         */
        responseJsonObj = (JSONObject) parser.parse(entityString);
    } catch (ClientProtocolException e) {
        LOG.error("Nud RPC Connection problem:" + e.toString());
        this.connected = false;
    } catch (IOException e) {
        LOG.error("Nud RPC Connection problem:" + e.toString());
        this.connected = false;
    } catch (ParseException ex) {
        LOG.error("Nud RPC Connection problem:" + ex.toString());
        this.connected = false;
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
    return responseJsonObj;
}

From source file:com.ba.masters.stock.BAStockAction.java

public ActionForward baGet(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    JSONObject json = new JSONObject();
    BAStockDTO vo = new BAStockDTO();
    try {/*w w w  .  j  a  va2  s  .com*/
        logger.info(" get method starts here");
        String stockId = request.getParameter("search");
        HashMap hashMpStockItemDet = BaStockFactory.getInstanceOfBaStockFactory().getStockItemDtls(stockId);
        json.put("exception", "");
        json.put("StockItemDets", hashMpStockItemDet);
        json.put("StockItemExit", hashMpStockItemDet.size());

        logger.warn("strCurrent PageNo ------------->" + objPageCount);

    } catch (Exception ex) {
        logger.error("The Exception is  :" + ex);
        ex.printStackTrace();
        json.put("exception", BAHandleAllException.exceptionHandler(ex));
    }
    response.getWriter().write(json.toString());
    return null;

}

From source file:gov.nih.nci.eagle.web.ajax.DynamicListHelper.java

public String getDetailsFromList(String listName) {
    WebContext ctx = WebContextFactory.get();
    String cacheId = ctx.getSession(false).getId();
    UserListBeanHelper ulbh = new UserListBeanHelper(cacheId);
    String jdetails = ulbh.getDetailsFromList(listName);
    Object o = JSONValue.parse(jdetails);
    //object [string -> listName], [string -> listType], [jsonArray->validItems]
    //validItems array of JSONObjects [name], [notes], [rank]
    JSONObject listDetails = (JSONObject) o;
    Object oo = listDetails.get("validItems");
    JSONArray validItems = (JSONArray) oo;
    for (Object ooo : validItems) {
        JSONObject itemDesc = (JSONObject) ooo;
        //see which specimens this item has
        ArrayList specimens = new ArrayList();
        for (SpecimenType sp : SpecimenType.values()) {
            List justone = new ArrayList();
            justone.add(itemDesc.get("name"));
            List shouldbeone = listValidationService.validateList(justone, sp);
            if (shouldbeone.size() == 1) {
                //hit
                specimens.add(sp.toString());
            } else {
                specimens.add("");
            }/* w  ww .  j  ava  2 s  . c  o  m*/
        }
        itemDesc.put("specimens", StringUtils.join(specimens.toArray(), ","));
    }

    return listDetails.toString();
}

From source file:com.ba.masters.tariff.BATariffAction.java

public ActionForward baGet(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    JSONObject json = new JSONObject();
    BATariffDTO vo = new BATariffDTO();
    try {/*from w  w w. j a v  a  2 s  . com*/
        logger.info(" get method starts here");
        String order = request.getParameter("search");
        HashMap hashMpTariffDet = BATariffFactory.getInstanceOfBATariffFactory().getTariffDtls(order);
        json.put("exception", "");
        json.put("TariffDets", hashMpTariffDet);
        json.put("TariffExit", hashMpTariffDet.size());

        //                 logger.warn("strCurrent PageNo ------------->"+objPageCount);
    } catch (Exception ex) {
        logger.error("The Exception is  :" + ex);
        ex.printStackTrace();
        json.put("exception", BAHandleAllException.exceptionHandler(ex));
    }
    response.getWriter().write(json.toString());
    return null;

}

From source file:com.ba.masters.room.BARoomAction.java

public ActionForward baGet(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    JSONObject json = new JSONObject();
    BARoomDTO vo = new BARoomDTO();
    try {/*  w w w  . j av a2  s.  c o m*/
        logger.info(" get method starts here");
        String roomId = request.getParameter("search");
        HashMap hashMpRoomItemDet = BARoomFactory.getInstanceOfBARoomFactory().getRoomDtls(roomId);
        json.put("exception", "");
        json.put("RoomDets", hashMpRoomItemDet);
        json.put("RoomExit", hashMpRoomItemDet.size());

        //                 logger.warn("strCurrent PageNo ------------->"+objPageCount);
    } catch (Exception ex) {
        logger.error("The Exception is  :" + ex);
        ex.printStackTrace();
        json.put("exception", BAHandleAllException.exceptionHandler(ex));
    }
    response.getWriter().write(json.toString());
    return null;

}

From source file:it.infn.ct.ToscaIDCInterface.java

/**
 * Load from <task_id>.json file command parameters.
 *//*from   w  w  w.  j a v a 2s . com*/
public final void loadJSONTask() {
    org.json.JSONObject jsonJobDesc = null;
    try {
        // Front-end prepares the task_id.json file describing the command
        String jobDescFileName = toscaCommand.getActionInfo() + FS + toscaCommand.getTaskId() + ".json";
        // Processing the JSON file
        LOG.debug("Reading JSON filename: '" + jobDescFileName + "'");

        InputStream is = new FileInputStream(jobDescFileName);
        String jsonTxt = IOUtils.toString(is);
        jsonJobDesc = (org.json.JSONObject) new org.json.JSONObject(jsonTxt);
        LOG.debug("Loaded APIServer JobDesc:\n" + LS + jsonJobDesc);

        // Username (unused yet but later used for accounting)
        user = String.format("%s", jsonJobDesc.getString("user"));
        LOG.debug("User: '" + user + "'");

        // Get app Info and Parameters
        org.json.JSONObject appInfo = new org.json.JSONObject();
        appInfo = jsonJobDesc.getJSONObject("application");
        JSONArray appParams = new JSONArray();
        appParams = appInfo.getJSONArray("parameters");

        // Application parameters
        String arguments = "";

        for (int i = 0; i < appParams.length(); i++) {
            org.json.JSONObject appParameter = appParams.getJSONObject(i);

            // Get parameter name and value
            String paramName = appParameter.getString("param_name");
            String paramValue = appParameter.getString("param_value");

            switch (paramName) {
            case "target_executor":
                LOG.debug("target_executor: '" + paramValue + "'");
                break;

            case "jobdesc_executable":
                executable = paramValue;
                LOG.debug("executable: '" + executable + "'");
                break;

            case "jobdesc_output":
                output = paramValue;
                toscaOutput = output;
                LOG.debug("output: '" + output + "'");
                break;
            case "jobdesc_error":
                error = paramValue;
                toscaError = error;
                LOG.debug("error: '" + error + "'");
                break;
            case "jobdesc_arguments":
                arguments = paramValue;
                LOG.debug("arguments: '" + arguments + "'");
                break;
            default:
                LOG.warn("Unsupported application parameter name: '" + paramName + "' with value: '"
                        + paramValue + "'");
            }
        }

        // Arguments
        String jobArgs = arguments;
        JSONArray jobArguments = jsonJobDesc.getJSONArray("arguments");
        for (int j = 0; j < jobArguments.length(); j++) {
            jobArgs += ((jobArgs.length() > 0) ? "," : "") + jobArguments.getString(j);
        }
        args = jobArgs.split(",");
        for (int k = 0; k < args.length; k++) {
            LOG.debug("args[" + k + "]: '" + args[k] + "'");
        }

        // Infrastructures
        // Select one of the possible infrastructures among the enabled
        // ones a random strategy is currently implemented; this could be
        // changed later
        JSONArray jobInfrastructures = appInfo.getJSONArray("infrastructures");
        JSONArray enabledInfras = new JSONArray();

        for (int v = 0, w = 0; w < jobInfrastructures.length(); w++) {
            org.json.JSONObject infra = jobInfrastructures.getJSONObject(w);

            if (infra.getString("status").equals("enabled")) {
                enabledInfras.put(v++, infra);
            }
        }

        int selInfraIdx = 0;
        Random rndGen = new Random();

        if (enabledInfras.length() > 1) {
            selInfraIdx = rndGen.nextInt(enabledInfras.length());
        }

        // Extract selected infrastructure
        org.json.JSONObject selInfra = new org.json.JSONObject();
        selInfra = enabledInfras.getJSONObject(selInfraIdx);
        LOG.debug("Selected infra: '" + LS + selInfra.toString() + "'");

        // Infrastructure parameters
        JSONArray infraParams = selInfra.getJSONArray("parameters");

        for (int h = 0; h < infraParams.length(); h++) {
            org.json.JSONObject infraParameter = infraParams.getJSONObject(h);
            String paramName = infraParameter.getString("name");
            String paramValue = infraParameter.getString("value");

            switch (paramName) {
            case "tosca_endpoint":
                toscaEndPoint = new URL(paramValue);
                toscaCommand.setRunTimeData("tosca_endpoint", toscaEndPoint.toString(), "TOSCA endpoint", "",
                        "");
                LOG.debug("tosca_endpoint: '" + toscaEndPoint + "'");
                break;
            case "tosca_template":
                toscaTemplate = toscaCommand.getActionInfo() + "/" + paramValue;
                LOG.debug("tosca_template: '" + toscaTemplate + "'");
                break;
            case "tosca_parameters":
                toscaParameters += ((toscaParameters.length() > 0) ? "&" : "") + paramValue;
                LOG.debug("tosca_parameters: '" + toscaParameters + "'");
                break;
            default:
                LOG.warn("Ignoring infrastructure parameter name: '" + paramName + "' with value: '"
                        + paramValue + "'");
            }
        }

        // Prepare JSAGA IO file list
        JSONArray inputFiles = jsonJobDesc.getJSONArray("input_files");

        for (int i = 0; i < inputFiles.length(); i++) {
            org.json.JSONObject fileEntry = inputFiles.getJSONObject(i);
            String fileName = fileEntry.getString("name");

            ioFiles += ((ioFiles.length() > 0) ? "," : "") + toscaCommand.getActionInfo() + FS
                    + fileEntry.getString("name") + ">" + fileEntry.getString("name");
        }

        JSONArray outputFiles = jsonJobDesc.getJSONArray("output_files");

        for (int j = 0; j < outputFiles.length(); j++) {
            org.json.JSONObject fileEntry = outputFiles.getJSONObject(j);
            String fileName = fileEntry.getString("name");

            ioFiles += ((ioFiles.length() > 0) ? "," : "") + toscaCommand.getActionInfo() + FS + JO + FS
                    + fileEntry.getString("name") + "<" + fileEntry.getString("name");
        }
        LOG.debug("IOFiles: '" + ioFiles + "'");

        files = ioFiles.split(",");
        for (int i = 0; i < files.length; i++) {
            LOG.debug("IO Files[" + i + "]: '" + files[i] + "'");
        }

        LOG.debug("JSON filename: '" + jobDescFileName + "' successfully read");
    } catch (Exception ex) {
        LOG.error("Caught exception: '" + ex.toString() + "'");
    }
}

From source file:edu.illinois.cs.cogcomp.wikifier.utils.freebase.QueryMQL.java

/**
 * returns the mid for a wiki title// w w w . j a  v a  2  s .com
 * 
 * @param mql
 * @return
 * @throws Exception
 */
@Deprecated
public String lookupMid(MQLQueryWrapper mql) throws Exception {
    String mqlQuery = mql.MQLquery;
    String title = mql.value;
    String checksum = getMD5Checksum(title);

    logger.debug("MQLQUERY is " + mqlQuery);
    JSONObject response;

    if (IOUtils.exists(midCacheLocation + "/" + checksum + ".cached")) {
        System.out.println("Found!");
        JSONParser jsonParser = new JSONParser();
        response = (JSONObject) jsonParser.parse(
                FileUtils.readFileToString(new File(midCacheLocation + "/" + checksum + ".cached"), "UTF-8"));
    } else {
        System.out.println("Caching");
        response = getResponse(mqlQuery);
        FileUtils.writeStringToFile(new File(midCacheLocation + "/" + checksum + ".cached"),
                response.toString(), "UTF-8");
    }

    JSONObject result = (JSONObject) response.get("result");
    if (result != null)
        return (String) result.get("mid");
    else
        return null;
}

From source file:com.ba.masters.staff.BAStaffAction.java

public ActionForward baGet(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    JSONObject json = new JSONObject();
    BAStaffDTO vo = new BAStaffDTO();
    try {//  w w  w  .j  a  v  a 2 s.c o  m
        logger.info(" get method starts here");
        String staffId = request.getParameter("search");
        HashMap hashMpStaffItemDet = BaStaffFactory.getInstanceOfBaStaffFactory().getStaffItemDtls(staffId);
        json.put("exception", "");
        json.put("StaffItemDets", hashMpStaffItemDet);
        json.put("StaffItemExit", hashMpStaffItemDet.size());

        logger.warn("strCurrent PageNo ------------->" + objPageCount);
    } catch (Exception ex) {
        logger.error("The Exception is  :" + ex);
        ex.printStackTrace();
        json.put("exception", BAHandleAllException.exceptionHandler(ex));
    }
    response.getWriter().write(json.toString());
    return null;

}