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:com.megacasting_ppe.web.ServletLoadOffreView.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from w w  w  . ja v a2 s  . c om
 *
 * @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 {
    response.setContentType("application/json");
    response.setHeader("Cache-Control", "no-cache");
    HttpSession session = request.getSession();

    JSONObject global = (JSONObject) session.getAttribute("offres_lib");

    Candidat candidat = (Candidat) session.getAttribute("CandidatObject");
    String connecterOk = (String) session.getAttribute("Connecter");

    if (candidat != null && connecterOk != null) {

        JSONObject infoAuth = new JSONObject();

        infoAuth.put("Nom", candidat.getNom());
        infoAuth.put("Prenom", candidat.getPrenom());
        infoAuth.put("connecter", connecterOk);

        global.put("infoauth", infoAuth);

    } else {

        JSONObject infoAuth = new JSONObject();
        infoAuth.put("connecter", "false");

        global.put("infoauth", infoAuth);
    }

    try (PrintWriter out = response.getWriter()) {
        out.println(global.toString());
    }

}

From source file:com.rackspacecloud.blueflood.outputs.handlers.HttpRollupsQueryHandler.java

@Override
public void handle(ChannelHandlerContext ctx, HttpRequest request) {

    Tracker.track(request);//from   www.  j a v a 2  s.co  m

    final String tenantId = request.getHeader("tenantId");
    final String metricName = request.getHeader("metricName");

    if (!(request instanceof HTTPRequestWithDecodedQueryParams)) {
        sendResponse(ctx, request, "Missing query params: from, to, points", HttpResponseStatus.BAD_REQUEST);
        return;
    }

    HTTPRequestWithDecodedQueryParams requestWithParams = (HTTPRequestWithDecodedQueryParams) request;

    final Timer.Context httpMetricsFetchTimerContext = httpMetricsFetchTimer.time();
    try {
        RollupsQueryParams params = PlotRequestParser.parseParams(requestWithParams.getQueryParams());

        JSONObject metricData;
        if (params.isGetByPoints()) {
            metricData = GetDataByPoints(tenantId, metricName, params.getRange().getStart(),
                    params.getRange().getStop(), params.getPoints(), params.getStats());
        } else if (params.isGetByResolution()) {
            metricData = GetDataByResolution(tenantId, metricName, params.getRange().getStart(),
                    params.getRange().getStop(), params.getResolution(), params.getStats());
        } else {
            throw new InvalidRequestException(
                    "Invalid rollups query. Neither points nor resolution specified.");
        }

        final JsonElement element = parser.parse(metricData.toString());
        final String jsonStringRep = gson.toJson(element);
        sendResponse(ctx, request, jsonStringRep, HttpResponseStatus.OK);
    } catch (InvalidRequestException e) {
        // let's not log the full exception, just the message.
        log.warn(e.getMessage());
        sendResponse(ctx, request, e.getMessage(), HttpResponseStatus.BAD_REQUEST);
    } catch (SerializationException e) {
        log.error(e.getMessage(), e);
        sendResponse(ctx, request, e.getMessage(), HttpResponseStatus.INTERNAL_SERVER_ERROR);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        sendResponse(ctx, request, e.getMessage(), HttpResponseStatus.INTERNAL_SERVER_ERROR);
    } finally {
        httpMetricsFetchTimerContext.stop();
    }
}

From source file:bbdn.lti2.LTI2Servlet.java

@SuppressWarnings("unused")
public void handleSettingsRequest(HttpServletRequest request, HttpServletResponse response, String[] parts)
        throws java.io.IOException {

    String URL = request.getRequestURL().toString();
    System.out.println("URL=" + URL);
    String scope = parts[4];/*from   www .j a  va 2  s  .co m*/
    System.out.println("scope=" + scope);

    String acceptHdr = request.getHeader("Accept");
    String contentHdr = request.getContentType();
    boolean acceptComplex = acceptHdr == null || acceptHdr.indexOf(StandardServices.TOOLSETTINGS_FORMAT) >= 0;

    System.out.println("accept=" + acceptHdr + " ac=" + acceptComplex);

    // Check the JSON on PUT and check the oauth_body_hash
    IMSJSONRequest jsonRequest = null;
    JSONObject requestData = null;
    if ("PUT".equals(request.getMethod())) {
        try {
            jsonRequest = new IMSJSONRequest(request);
            requestData = (JSONObject) JSONValue.parse(jsonRequest.getPostBody());
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            doErrorJSON(request, response, jsonRequest, "Could not parse JSON", e);
            return;
        }
    }

    String consumer_key = "42";
    String profile = (String) PERSIST.get("profile");
    JSONObject providerProfile = (JSONObject) JSONValue.parse(profile);
    JSONObject security_contract = (JSONObject) providerProfile.get(LTI2Constants.SECURITY_CONTRACT);
    String oauth_secret = (String) security_contract.get(LTI2Constants.SHARED_SECRET);

    // Validate the incoming message
    Object retval = BasicLTIUtil.validateMessage(request, URL, oauth_secret, consumer_key);
    if (retval instanceof String) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        doErrorJSON(request, response, jsonRequest, (String) retval, null);
        return;
    }

    // The URLs for the various settings resources
    String settingsUrl = getServiceURL(request) + SVC_Settings;
    String proxy_url = settingsUrl + "/" + LTI2Util.SCOPE_ToolProxy + "/" + consumer_key;
    String binding_url = settingsUrl + "/" + LTI2Util.SCOPE_ToolProxyBinding + "/" + "TBD";
    String link_url = settingsUrl + "/" + LTI2Util.SCOPE_LtiLink + "/" + "TBD";

    // Load and parse the old settings...
    JSONObject link_settings = LTI2Util.parseSettings((String) PERSIST.get(LTI2Util.SCOPE_LtiLink));
    JSONObject binding_settings = LTI2Util.parseSettings((String) PERSIST.get(LTI2Util.SCOPE_ToolProxyBinding));
    JSONObject proxy_settings = LTI2Util.parseSettings((String) PERSIST.get(LTI2Util.SCOPE_ToolProxy));

    // For a GET request we depend on LTI2Util to do the GET logic
    if ("GET".equals(request.getMethod())) {
        Object obj = LTI2Util.getSettings(request, scope, link_settings, binding_settings, proxy_settings,
                link_url, binding_url, proxy_url);

        if (obj instanceof String) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            doErrorJSON(request, response, jsonRequest, (String) obj, null);
            return;
        }

        if (acceptComplex) {
            response.setContentType(StandardServices.TOOLSETTINGS_FORMAT);
        } else {
            response.setContentType(StandardServices.TOOLSETTINGS_SIMPLE_FORMAT);
        }

        JSONObject jsonResponse = (JSONObject) obj;
        response.setStatus(HttpServletResponse.SC_OK);
        PrintWriter out = response.getWriter();
        System.out.println("jsonResponse=" + jsonResponse);
        out.println(jsonResponse.toString());
        return;
    } else if ("PUT".equals(request.getMethod())) {
        // This is assuming the rule that a PUT of the complex settings
        // format that there is only one entry in the graph and it is
        // the same as our current URL.  We parse without much checking.
        String settings = null;
        try {
            JSONArray graph = (JSONArray) requestData.get(LTI2Constants.GRAPH);
            if (graph.size() != 1) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                doErrorJSON(request, response, jsonRequest, "Only one graph entry allowed", null);
                return;
            }
            JSONObject firstChild = (JSONObject) graph.get(0);
            JSONObject custom = (JSONObject) firstChild.get(LTI2Constants.CUSTOM);
            settings = custom.toString();
        } catch (Exception e) {
            settings = jsonRequest.getPostBody();
        }
        PERSIST.put(scope, settings);
        System.out.println("Stored settings scope=" + scope);
        System.out.println("settings=" + settings);
        response.setStatus(HttpServletResponse.SC_OK);
    } else {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "Method not handled=" + request.getMethod(), null);
    }
}

From source file:com.ba.reports.DayReport.BADayReportAction.java

public ActionForward baGet(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    JSONObject json = new JSONObject();
    BADayReportDTO vo = new BADayReportDTO();
    try {//  w w w.jav a 2s.  c  om
        logger.info(" get method starts here");
        String roomId = request.getParameter("search");
        HashMap hashMpRoomItemDet = BADayReportFactory.getInstanceOfBADayReportFactory().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:com.dubture.twig.core.index.TwigIndexingVisitorExtension.java

@SuppressWarnings("unchecked")
@Override/* w ww  . ja v a2 s.c o m*/
public boolean endvisit(TypeDeclaration s) throws Exception {
    if (s instanceof ClassDeclaration) {
        if (tag != null) {
            if (tag.getStartTag() != null) {

                int length = currentClass.sourceEnd() - currentClass.sourceStart();
                PHPDocBlock block = currentClass.getPHPDoc();
                String desc = "";
                if (block != null) {
                    String shortDesc = block.getShortDescription() != null ? block.getShortDescription() : "";
                    String longDesc = block.getLongDescription() != null ? block.getLongDescription() : "";
                    desc = shortDesc + longDesc;
                }

                String endTag = tag.getEndTag();

                JSONObject metadata = new JSONObject();
                metadata.put(TwigType.PHPCLASS, currentClass.getName());
                metadata.put(TwigType.DOC, desc);
                metadata.put(TwigType.IS_OPEN_CLOSE, endTag != null);

                Logger.debugMSG("indexing twig tag: " + tag.getStartTag() + " : " + tag.getEndTag()
                        + " with metadata: " + metadata.toString());

                ReferenceInfo info = new ReferenceInfo(ITwigModelElement.START_TAG, currentClass.sourceStart(),
                        length, tag.getStartTag(), metadata.toString(), null);
                addReferenceInfo(info);

                if (endTag != null) {
                    ReferenceInfo endIinfo = new ReferenceInfo(ITwigModelElement.END_TAG,
                            currentClass.sourceStart(), length, tag.getEndTag(), metadata.toString(), null);
                    addReferenceInfo(endIinfo);
                }

            }
            tag = null;
        }

        inTwigExtension = false;
        inTokenParser = false;
        currentClass = null;
    }

    return false;
}

From source file:io.personium.test.jersey.cell.ctl.RoleCreateTest.java

/**
     * ?????????().//from w w w. j av a2 s  . c  om
     * @param roleName
     * @param boxname
     * @param ?
     * @return 
     */
    @SuppressWarnings("unchecked")
    private TResponse createRole(String roleName, String boxname) {
        JSONObject body = new JSONObject();
        body.put("Name", roleName);
        body.put("_Box.Name", boxname);

        return Http.request("role-create.txt").with("token", AbstractCase.MASTER_TOKEN_NAME)
                .with("cellPath", cellName).with("body", body.toString()).returns().debug();
    }

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

private JSONObject saveScript(final String name, final String description, final String content)
        throws Exception {
    if (StringUtils.trimToNull(name) == null) {
        log.error("Invalid input script name: " + name);
        return null;
    }/*from   www .  j a v a  2s .c om*/
    if (StringUtils.trimToNull(content) == null) {
        log.error("Invalid input script content.");
        return null;
    }

    boolean canExport = validateExport(content);
    if (!uploadDirExists()) {
        FileUtils.forceMkdir(getUploadDir());
    }

    File fScript = new File(scriptFolder + "/" + name + ".js");

    if (!fScript.exists()) {
        fScript.createNewFile();
    }
    String header = headerStart;
    JSONObject oHeader = new JSONObject();
    oHeader.put("NAME", name);
    oHeader.put("DESCRIPTION", description);
    oHeader.put("CANEXPORT", canExport);

    header += oHeader.toString();
    header += headerEnd;

    FileUtils.writeStringToFile(fScript, header + content);

    log.debug("Saved script: " + name);

    return oHeader;
}

From source file:com.photon.phresco.util.Utility.java

public static void writeProcessid(String baseDir, String key, String pid) {
    if (StringUtils.isEmpty(baseDir) || StringUtils.isEmpty(key)) {
        return;/*  ww  w  .  j  a va 2  s.co m*/
    }
    File do_not_checkin = new File(baseDir + File.separator + DO_NOT_CHECKIN_DIRY);
    if (!do_not_checkin.exists()) {
        do_not_checkin.mkdirs();
    }
    File jsonFile = new File(do_not_checkin.getPath() + File.separator + "process.json");
    JSONObject jsonObject = new JSONObject();
    JSONParser parser = new JSONParser();
    try {
        if (jsonFile.exists()) {
            FileReader reader = new FileReader(jsonFile);
            jsonObject = (JSONObject) parser.parse(reader);
        }
        jsonObject.put(key, pid);
        FileWriter writer = new FileWriter(jsonFile);
        writer.write(jsonObject.toString());
        writer.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:jp.aegif.nemaki.rest.GroupResource.java

@SuppressWarnings("unchecked")
@GET//from w  w  w . j  a  va 2 s . c  o  m
@Path("/show/{id}")
@Produces(MediaType.APPLICATION_JSON)
public String show(@PathParam("repositoryId") String repositoryId, @PathParam("id") String groupId) {
    boolean status = true;
    JSONObject result = new JSONObject();
    JSONArray errMsg = new JSONArray();

    Group group = principalService.getGroupById(repositoryId, groupId);
    if (group == null) {
        status = false;
        addErrMsg(errMsg, ITEM_GROUP, ErrorCode.ERR_NOTFOUND);
    } else {
        result.put("group", convertGroupToJson(group));
    }
    makeResult(status, result, errMsg);
    return result.toString();
}

From source file:com.nubits.nubot.options.NuBotOptions.java

private String toStringNoKeys() {
    String toRet = "";

    GsonBuilder gson = new GsonBuilder().setPrettyPrinting();
    //gson.registerTypeAdapter(NuBotOptions.class, new NuBotOptionsSerializer());
    Gson parser = gson.create();/*from   w ww .  ja  v a 2s.c  o m*/

    String serializedOptionsStr = parser.toJson(this);
    org.json.simple.parser.JSONParser p = new org.json.simple.parser.JSONParser();
    try {
        JSONObject serializedOptionsJSON = (JSONObject) (p.parse(serializedOptionsStr));

        //Replace sensitive information
        String[] sensitiveKeys = { "apisecret", "apikey", "rpcpass", "apiSecret", "apiKey", "rpcPass" };
        String replaceString = "hidden";

        for (int i = 0; i < sensitiveKeys.length; i++) {
            if (serializedOptionsJSON.containsKey(sensitiveKeys[i])) {
                serializedOptionsJSON.replace(sensitiveKeys[i], replaceString);
            }
        }

        toRet = serializedOptionsJSON.toString();
    } catch (org.json.simple.parser.ParseException e) {
        LOG.error(e.toString());
    }

    return toRet;
}