Example usage for org.json JSONObject toString

List of usage examples for org.json JSONObject toString

Introduction

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

Prototype

public String toString(int indentFactor) throws JSONException 

Source Link

Document

Make a prettyprinted JSON text of this JSONObject.

Usage

From source file:org.loklak.api.iot.ImportProfileServlet.java

private void doUpdate(Query post, HttpServletResponse response) throws IOException {
    String callback = post.get("callback", null);
    boolean jsonp = callback != null && callback.length() > 0;
    String data = post.get("data", "");
    if (data == null || data.length() == 0) {
        response.sendError(400, "your request must contain a data object.");
        return;//from  ww  w . ja va 2  s  .co  m
    }

    // parse the json data
    boolean success;

    try {
        JSONObject json = null;
        try {
            json = new JSONObject(data);
        } catch (JSONException e) {
        }
        if (json == null) {
            throw new IOException("cannot parse json");
        }
        if (!json.has("id_str")) {
            throw new IOException("id_str field missing");
        }
        if (!json.has("source_type")) {
            throw new IOException("source_type field missing");
        }
        ImportProfileEntry i = DAO.SearchLocalImportProfiles(json.getString("id_str"));
        if (i == null) {
            throw new IOException("import profile id_str field '" + json.getString("id_str") + "' not found");
        }
        ImportProfileEntry importProfileEntry;
        try {
            importProfileEntry = new ImportProfileEntry(json);
        } catch (IllegalArgumentException e) {
            response.sendError(400, "Error updating import profile : " + e.getMessage());
            return;
        }
        importProfileEntry.setLastModified(new Date());
        success = DAO.writeImportProfile(importProfileEntry, true);
    } catch (IOException | NullPointerException e) {
        response.sendError(400, "submitted data is invalid : " + e.getMessage());
        Log.getLog().warn(e);
        return;
    }

    post.setResponse(response, "application/javascript");
    JSONObject json = new JSONObject(true);
    json.put("status", "ok");
    json.put("records", success ? 1 : 0);
    json.put("message", "updated");
    // write json
    response.setCharacterEncoding("UTF-8");
    PrintWriter sos = response.getWriter();
    if (jsonp)
        sos.print(callback + "(");
    sos.print(json.toString(2));
    if (jsonp)
        sos.println(");");
    sos.println();
    post.finalize();
}

From source file:io.teak.sdk.Teak.java

/**************************************************************************/

@SuppressWarnings("unused")
private static void openIABPurchaseSucceeded(String json) {
    try {//from  w ww .j  a  v a 2  s.c o  m
        JSONObject purchase = new JSONObject(json);
        if (Teak.isDebug) {
            Log.d(LOG_TAG, "OpenIAB purchase succeeded: " + purchase.toString(2));
        }

        if (Teak.appStore != null && Teak.appStore.ignorePluginPurchaseEvents()) {
            if (Teak.isDebug) {
                Log.d(LOG_TAG, "OpenIAB callback ignored, store purchase reporting is auto-magical.");
            }
        } else {
            JSONObject originalJson = new JSONObject(purchase.getString("originalJson"));
            purchaseSucceeded(originalJson);
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, Log.getStackTraceString(e));
        Teak.sdkRaven.reportException(e);
    }
}

From source file:io.teak.sdk.Teak.java

@SuppressWarnings("unused")
private static void prime31PurchaseSucceeded(String json) {
    try {/*  w w  w . jav a2 s .com*/
        JSONObject originalJson = new JSONObject(json);
        if (Teak.isDebug) {
            Log.d(LOG_TAG, "Prime31 purchase succeeded: " + originalJson.toString(2));
        }

        if (Teak.appStore != null && Teak.appStore.ignorePluginPurchaseEvents()) {
            if (Teak.isDebug) {
                Log.d(LOG_TAG, "Prime31 callback ignored, store purchase reporting is auto-magical.");
            }
        } else {
            purchaseSucceeded(originalJson);
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, Log.getStackTraceString(e));
        Teak.sdkRaven.reportException(e);
    }
}

From source file:io.teak.sdk.Teak.java

static void purchaseSucceeded(final JSONObject purchaseData) {
    Teak.asyncExecutor.submit(new Runnable() {
        public void run() {
            try {
                if (Teak.isDebug) {
                    Log.d(LOG_TAG, "Purchase succeeded: " + purchaseData.toString(2));
                }// www .  j a  v a  2 s  .  co  m

                final HashMap<String, Object> payload = new HashMap<>();

                if (Teak.appConfiguration.installerPackage == null) {
                    Log.e(LOG_TAG, "Purchase succeded from unknown app store.");
                } else if (Teak.appConfiguration.installerPackage.equals("com.amazon.venezia")) {
                    JSONObject receipt = purchaseData.getJSONObject("receipt");
                    JSONObject userData = purchaseData.getJSONObject("userData");

                    payload.put("purchase_token", receipt.get("receiptId"));
                    payload.put("purchase_time_string", receipt.get("purchaseDate"));
                    payload.put("product_id", receipt.get("sku"));
                    payload.put("store_user_id", userData.get("userId"));
                    payload.put("store_marketplace", userData.get("marketplace"));

                    Log.d(LOG_TAG, "Purchase of " + receipt.get("sku") + " detected.");
                } else {
                    payload.put("purchase_token", purchaseData.get("purchaseToken"));
                    payload.put("purchase_time", purchaseData.get("purchaseTime"));
                    payload.put("product_id", purchaseData.get("productId"));
                    if (purchaseData.has("orderId")) {
                        payload.put("order_id", purchaseData.get("orderId"));
                    }

                    Log.d(LOG_TAG, "Purchase of " + purchaseData.get("productId") + " detected.");
                }

                if (Teak.appStore != null) {
                    JSONObject skuDetails = Teak.appStore.querySkuDetails((String) payload.get("product_id"));
                    if (skuDetails != null) {
                        if (skuDetails.has("price_amount_micros")) {
                            payload.put("price_currency_code", skuDetails.getString("price_currency_code"));
                            payload.put("price_amount_micros", skuDetails.getString("price_amount_micros"));
                        } else if (skuDetails.has("price_string")) {
                            payload.put("price_string", skuDetails.getString("price_string"));
                        }
                    }
                }

                Session.whenUserIdIsReadyRun(new Session.SessionRunnable() {
                    @Override
                    public void run(Session session) {
                        new Request("/me/purchase", payload, session).run();
                    }
                });
            } catch (Exception e) {
                Log.e(LOG_TAG, "Error reporting purchase: " + Log.getStackTraceString(e));
                Teak.sdkRaven.reportException(e);
            }
        }
    });
}

From source file:com.tesobe.obp.transport.spi.ConnectorNov2016Test.java

@Test
public void describe() throws Exception {
    String json = connector.describe();
    JSONObject description = new JSONObject(json);

    assertThat(description.opt("error"), nullValue());

    System.out.println(description.toString(2));
}

From source file:org.loklak.api.server.AppsServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    RemoteAccess.Post post = RemoteAccess.evaluate(request);

    String callback = post.get("callback", "");
    boolean jsonp = callback != null && callback.length() > 0;
    post.setResponse(response, "application/javascript");

    // generate json
    File apps = new File(DAO.html_dir, "apps");
    JSONObject json = new JSONObject(true);
    JSONArray app_array = new JSONArray();
    json.put("apps", app_array);
    for (String appname : apps.list())
        try {/*from  ww w  . jav a 2  s  .co m*/
            File apppath = new File(apps, appname);
            if (!apppath.isDirectory())
                continue;
            Set<String> files = new HashSet<>();
            for (String f : apppath.list())
                files.add(f);
            if (!files.contains("index.html"))
                continue;
            if (!files.contains("app.json"))
                continue;
            File json_ld_file = new File(apppath, "app.json");
            Map<String, Object> json_ld_map = DAO.jsonMapper.readValue(json_ld_file, DAO.jsonTypeRef);
            JSONObject json_ld = new JSONObject(json_ld_map);
            app_array.put(json_ld);
        } catch (Throwable e) {
            Log.getLog().warn(e);
        }

    // write json
    response.setCharacterEncoding("UTF-8");
    FileHandler.setCaching(response, 60);
    PrintWriter sos = response.getWriter();
    if (jsonp)
        sos.print(callback + "(");
    sos.print(json.toString(2));
    if (jsonp)
        sos.println(");");
    sos.println();

    post.finalize();
}

From source file:org.loklak.api.iot.NOAAAlertServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Query post = RemoteAccess.evaluate(request);

    // manage DoS
    if (post.isDoS_blackout()) {
        response.sendError(503, "your request frequency is too high");
        return;/*from  w ww  .ja  v a  2 s  . c o m*/
    }

    String content = new String(Files.readAllBytes(Paths.get(DAO.conf_dir + "/iot/scripts/counties.xml")));
    try {
        // Conversion of the XML Layers through PERL into the required JSON for well structured XML
        /*
        <resources>
        <string-array name="preference_county_entries_us">
            <item>Entire Country</item>
        </string-array>
        <string-array name="preference_county_entryvalues_us">
            <item>https://alerts.weather.gov/cap/us.php?x=0</item>
        </string-array>
        .
        .
        .
        Similarly every 2 DOM elements together in <resources> constitute a pair.
        </resources>
        */
        JSONObject json = XML.toJSONObject(content);
        PrintWriter sos = response.getWriter();
        JSONObject resourceObject = json.getJSONObject("resources");
        JSONArray stringArray = resourceObject.getJSONArray("string-array");
        JSONObject result = new JSONObject(true);

        // Extract and map the itemname and the url strings
        /*
        {
        "item": "Entire Country",
        "name": "preference_county_entries_us"
        },
        {
        "item": "https://alerts.weather.gov/cap/us.php?x=0",
        "name": "preference_county_entryvalues_us"
        }
        */
        for (int i = 0; i < stringArray.length(); i += 2) {
            JSONObject keyJSONObject = stringArray.getJSONObject(i);
            JSONObject valueJSONObject = stringArray.getJSONObject(i + 1);
            Object kItemObj = keyJSONObject.get("item");
            Object vItemObj = valueJSONObject.get("item");

            // Since instances are variable, we need to check if they're Arrays or Strings
            // The processing for the Key : Value mappings will change for each type of instance
            if (kItemObj instanceof JSONArray) {
                if (vItemObj instanceof JSONArray) {
                    JSONArray kArray = keyJSONObject.getJSONArray("item");
                    JSONArray vArray = valueJSONObject.getJSONArray("item");
                    for (int location = 0; location < kArray.length(); location++) {
                        String kValue = kArray.getString(location);
                        String vValue = vArray.getString(location);
                        result.put(kValue, vValue);
                    }
                }
            } else {
                // They are plain strings
                String kItemValue = keyJSONObject.getString("item");
                String vItemValue = valueJSONObject.getString("item");
                result.put(kItemValue, vItemValue);
            }

        }
        // Sample response in result has to be something like
        /*
        {
        "Entire Country": "https://alerts.weather.gov/cap/us.php?x=0",
        "Entire State": "https://alerts.weather.gov/cap/wy.php?x=0",
        "Autauga": "https://alerts.weather.gov/cap/wwaatmget.php?x=ALC001&y=0",
        "Baldwin": "https://alerts.weather.gov/cap/wwaatmget.php?x=GAC009&y=0",
        "Barbour": "https://alerts.weather.gov/cap/wwaatmget.php?x=WVC001&y=0",
        "Bibb": "https://alerts.weather.gov/cap/wwaatmget.php?x=GAC021&y=0",
        .
        .
        .
        And so on.
        }
        */

        sos.print(result.toString(2));
        sos.println();
    } catch (IOException e) {
        Log.getLog().warn(e);
        JSONObject json = new JSONObject(true);
        json.put("error", "Looks like there is an error in the conversion");
        json.put("type", "Error");
        PrintWriter sos = response.getWriter();
        sos.print(json.toString(2));
        sos.println();
    }

}

From source file:ai.susi.mind.SusiSkill.java

/**
 * Generate a set of skills from a single skill definition. This may be possible if the skill contains an 'options'
 * object which creates a set of skills, one for each option. The options combine with one set of phrases
 * @param json - a multi-skill definition
 * @return a set of skills//from  ww  w. ja  v a  2 s  .co  m
 */
public static List<SusiSkill> getSkills(JSONObject json) {
    if (!json.has("phrases"))
        throw new PatternSyntaxException("phrases missing", "", 0);
    final List<SusiSkill> skills = new ArrayList<>();
    if (json.has("options")) {
        JSONArray options = json.getJSONArray("options");
        for (int i = 0; i < options.length(); i++) {
            JSONObject option = new JSONObject();
            option.put("phrases", json.get("phrases"));
            JSONObject or = options.getJSONObject(i);
            for (String k : or.keySet())
                option.put(k, or.get(k));
            skills.add(new SusiSkill(option));
        }
    } else {
        try {
            SusiSkill skill = new SusiSkill(json);
            skills.add(skill);
        } catch (PatternSyntaxException e) {
            Logger.getLogger("SusiSkill")
                    .warning("Regular Expression error in Susi Skill: " + json.toString(2));
        }
    }
    return skills;
}

From source file:server.http.system.SysInfo.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setContentType("application/json;charset=UTF-8");
    try (PrintWriter out = res.getWriter()) {
        JSONObject root = new JSONObject();

        try {/*from   w  w  w.  j  a v a2s  .c  om*/

            JSONObject net = new JSONObject();
            net.put("Download_B", SystemInformation.DOWNLOAD);
            net.put("Upload_B", SystemInformation.UPLOAD);
            root.put("Network_B", net);

            //                JSONObject netF = new JSONObject();
            //                netF.put("Download_Fmt", SystemInformation.DOWNLOAD_FORMAT);
            //                netF.put("Upload_Fmt", SystemInformation.UPLOAD_FORMAT);
            //                root.put("Network_Fmt", netF);

            // ------------------------------------------- Cpu Sys
            JSONObject cpuSys = new JSONObject();
            int k = 0;
            for (int i : SystemInformation.CPU_USAGE) {
                cpuSys.put("Usage" + (k++), i);
            }
            cpuSys.put("UsageAll", SystemInformation.CPU_USAGE_ALL);
            root.put("CpuSys_%", cpuSys);

            // ------------------------------------------- Cpu App
            JSONObject cpuApp = new JSONObject();
            cpuApp.put("SysUsage", SystemInformation.CPU_USAGE_SYSTEM);
            cpuApp.put("AppUsage", SystemInformation.CPU_USAGE_APP);
            root.put("CpuApp_%", cpuApp);

            // ------------------------------------------- Thread Count App
            JSONObject appThread = new JSONObject();
            appThread.put("Count", SystemInformation.THREAD_COUNT);
            appThread.put("DaemonCount", SystemInformation.THREAD_COUNT_DAEMON);
            appThread.put("PeakCount", SystemInformation.THREAD_COUNT_PEAK);
            root.put("AppThread", appThread);

            // ------------------------------------------- Ram App
            JSONObject ramApp = new JSONObject();
            ramApp.put("Total", SystemInformation.RAM_TOTAL_MB);
            ramApp.put("Max", SystemInformation.RAM_MAX_MB);
            ramApp.put("Free", SystemInformation.RAM_FREE_MB);
            root.put("RamApp_MB", ramApp);

            // ------------------------------------------- Ram Sys
            JSONObject ramSys = new JSONObject();
            ramSys.put("PhysTotal", SystemInformation.TOTAL_PHYSICAL_MEMORY_SIZE_MB);
            ramSys.put("PhysFree", SystemInformation.FREE_PHYSICAL_MEMORY_SIZE_MB);
            ramSys.put("SwapTotal", SystemInformation.TOTAL_SWAP_SPACE_SIZE_MB);
            ramSys.put("SwapFree", SystemInformation.FREE_SWAP_SPACE_SIZE_MB);
            root.put("RamSys_MB", ramSys);

            // ------------------------------------------- Hdd Sys            
            JSONArray hddSys = new JSONArray();

            for (int i = 0; i < SystemInformation.HDD_NAME.size(); i++) {
                JSONObject hdd = new JSONObject();
                hdd.put("Name", SystemInformation.HDD_NAME.get(i));
                hdd.put("Total", SystemInformation.HDD_TOTAL_SPACE_GB.get(i));
                hdd.put("Free", SystemInformation.HDD_FREE_SPACE_GB.get(i));
                hddSys.put(hdd);
            }
            root.put("HddSys_GB", hddSys);
            // ------------------------------------------- Add Root
        } catch (Exception e) {
            out.print("error");
        }
        out.print(root.toString(4));//036670221
    }
}

From source file:com.xee.demo.utils.JsonLogger.java

/**
 * Get a json to format/*from   w ww .j  av a2s  . c o  m*/
 * @param message the json to format
 * @return the pretty json
 */
public static String getPrettyLog(String message) {
    String json;
    try {
        if (message.startsWith("{")) {
            JSONObject jsonObject = new JSONObject(message);
            json = jsonObject.toString(JSON_INDENT);
        } else if (message.startsWith("[")) {
            JSONArray jsonArray = new JSONArray(message);
            json = jsonArray.toString(JSON_INDENT);
        } else {
            json = message;
        }
    } catch (JSONException e) {
        json = message;
    }

    return json;
}