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() 

Source Link

Document

Make a JSON text of this JSONObject.

Usage

From source file:sh.calaba.driver.server.CalabashProxy.java

/**
 * Redirects the given calabash <code>command</code> to the calabash server of the corresponding
 * session. The command handling of taking screenshots is different from the other calabash
 * command because another URI is used.//from   w  w w .j  a  va2 s.  co m
 * 
 * @param command The command to redirect and execute.
 * @param sessionId The test session id.
 * @return The response of the calabash server running on the device.
 */
public JSONObject redirectMessageToCalabashServer(JSONObject command, String sessionId) {
    if (logger.isDebugEnabled()) {
        logger.debug("received command: " + command.toString());
        logger.debug("received sessionId: " + sessionId);
    }
    if (sessionConnectors.containsKey(sessionId)) {
        JSONObject result = null;
        try {
            if ("take_screenshot_embed".equals(command.get("command"))) {
                result = sessionConnectors.get(sessionId).takeScreenshot();
            } else {
                result = sessionConnectors.get(sessionId).execute(command);
            }
        } catch (JSONException e) {
            logger.error("Exception occured: ", e);
            throw new CalabashConnecterException("Json exception occured while executing calabash commands: ",
                    e);
        } catch (IOException e) {
            logger.error("Exception occured: ", e);
            throw new CalabashConnecterException(
                    "IOException exception occured while executing calabash commands: ", e);
        }

        return result;
    } else {
        throw new CalabashConnecterException("Calabash Connector for Session not found: " + sessionId);
    }
}

From source file:edu.cvrg.cvrg_timeseriesstore.AppTest.java

@Test
public void testQueryPOST() {

    boolean result = false;
    HashMap<String, String> tags = new HashMap<String, String>();
    tags.put("format", "hl7aecg");
    JSONObject array = TimeSeriesRetriever.retrieveTimeSeries(OPENTSDB_URL, 1420088400000L, 1425501345000L,
            "ecg.I.uv", tags);
    System.out.println(array.toString());
    assertTrue(array != null);//w  w w .  j  a v a 2  s.co m
}

From source file:com.saggezza.litracker.track.PayloadMapC.java

/**
 * {@inheritDoc}/*w  w w  .java2 s .com*/
 * @param dictInfo Information is parsed elsewhere from string to JSON then passed here
 * @param encode_base64 Whether or not to encode before transferring to web. Default true.
 * @return
 * @throws java.io.UnsupportedEncodingException
 */
public PayloadMap addUnstruct(JSONObject dictInfo, boolean encode_base64) throws UnsupportedEncodingException {
    //Encode parameter
    if (dictInfo == null)
        return this; //Catch this in contractor
    String json = dictInfo.toString();
    if (encode_base64) {
        json = base64encode(json);
        this.parameters.put("ue_px", json);
    } else
        this.parameters.put("ue_pr", json);
    return new PayloadMapC(this.parameters, this.configurations);
}

From source file:com.saggezza.litracker.track.PayloadMapC.java

/**
 * {@inheritDoc}/*  w w w  . ja  v a2 s .  c o m*/
 * @param jsonObject JSON object to be added
 * @param encode_base64 Whether or not to encode before transferring to web. Default true.
 * @return
 * @throws java.io.UnsupportedEncodingException
 */
public PayloadMap addJSON(JSONObject jsonObject, boolean encode_base64) throws UnsupportedEncodingException {
    //Encode parameter
    if (jsonObject == null) ///CATCH IF JSON LEFT NULL
        return this; ///need to figure out purpose of JSON
    String json = jsonObject.toString();
    if (encode_base64) {
        json = base64encode(json);
        this.parameters.put("cx", json);
    } else
        this.parameters.put("co", json);
    return new PayloadMapC(this.parameters, this.configurations);
}

From source file:fiskinfoo.no.sintef.fiskinfoo.MapFragment.java

private void createSearchDialog() {
    final Dialog dialog = dialogInterface.getDialog(getActivity(), R.layout.dialog_search_tools,
            R.string.search_tools_title);

    final ScrollView scrollView = (ScrollView) dialog.findViewById(R.id.search_tools_dialog_scroll_view);
    final AutoCompleteTextView inputField = (AutoCompleteTextView) dialog
            .findViewById(R.id.search_tools_input_field);
    final LinearLayout rowsContainer = (LinearLayout) dialog.findViewById(R.id.search_tools_row_container);
    final Button viewInMapButton = (Button) dialog.findViewById(R.id.search_tools_view_in_map_button);
    final Button jumpToBottomButton = (Button) dialog.findViewById(R.id.search_tools_jump_to_bottom_button);
    Button dismissButton = (Button) dialog.findViewById(R.id.search_tools_dismiss_button);

    List<PropertyDescription> subscribables;
    PropertyDescription newestSubscribable = null;
    final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss",
            Locale.getDefault());
    Date cachedUpdateDateTime;//from  ww  w  . ja v  a2 s  .  com
    Date newestUpdateDateTime;
    SubscriptionEntry cachedEntry;
    Response response;
    final JSONArray toolsArray;
    ArrayAdapter<String> adapter;
    String format = "JSON";
    String downloadPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
            .toString() + "/FiskInfo/Offline/";
    final JSONObject tools;
    final List<String> vesselNames;
    final Map<String, List<Integer>> toolIdMap = new HashMap<>();
    byte[] data = new byte[0];

    cachedEntry = user.getSubscriptionCacheEntry(getString(R.string.fishing_facility_api_name));

    if (fiskInfoUtility.isNetworkAvailable(getActivity())) {
        subscribables = barentswatchApi.getApi().getSubscribable();
        for (PropertyDescription subscribable : subscribables) {
            if (subscribable.ApiName.equals(getString(R.string.fishing_facility_api_name))) {
                newestSubscribable = subscribable;
                break;
            }
        }
    } else if (cachedEntry == null) {
        Dialog infoDialog = dialogInterface.getAlertDialog(getActivity(), R.string.tools_search_no_data_title,
                R.string.tools_search_no_data, -1);

        infoDialog.show();
        return;
    }

    if (cachedEntry != null) {
        try {
            cachedUpdateDateTime = simpleDateFormat
                    .parse(cachedEntry.mLastUpdated.equals(getActivity().getString(R.string.abbreviation_na))
                            ? "2000-00-00T00:00:00"
                            : cachedEntry.mLastUpdated);
            newestUpdateDateTime = simpleDateFormat
                    .parse(newestSubscribable != null ? newestSubscribable.LastUpdated : "2000-00-00T00:00:00");

            if (cachedUpdateDateTime.getTime() - newestUpdateDateTime.getTime() < 0) {
                response = barentswatchApi.getApi().geoDataDownload(newestSubscribable.ApiName, format);
                try {
                    data = FiskInfoUtility.toByteArray(response.getBody().in());
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (new FiskInfoUtility().writeMapLayerToExternalStorage(getActivity(), data,
                        newestSubscribable.Name.replace(",", "").replace(" ", "_"), format, downloadPath,
                        false)) {
                    SubscriptionEntry entry = new SubscriptionEntry(newestSubscribable, true);
                    entry.mLastUpdated = newestSubscribable.LastUpdated;
                    user.setSubscriptionCacheEntry(newestSubscribable.ApiName, entry);
                    user.writeToSharedPref(getActivity());
                }
            } else {
                String directoryFilePath = Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()
                        + "/FiskInfo/Offline/";

                File file = new File(directoryFilePath + newestSubscribable.Name + ".JSON");
                StringBuilder jsonString = new StringBuilder();
                BufferedReader bufferReader = null;

                try {
                    bufferReader = new BufferedReader(new FileReader(file));
                    String line;

                    while ((line = bufferReader.readLine()) != null) {
                        jsonString.append(line);
                        jsonString.append('\n');
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (bufferReader != null) {
                        try {
                            bufferReader.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                data = jsonString.toString().getBytes();
            }

        } catch (ParseException e) {
            e.printStackTrace();
            Log.e(TAG, "Invalid datetime provided");
        }
    } else {
        response = barentswatchApi.getApi().geoDataDownload(newestSubscribable.ApiName, format);
        try {
            data = FiskInfoUtility.toByteArray(response.getBody().in());
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (new FiskInfoUtility().writeMapLayerToExternalStorage(getActivity(), data,
                newestSubscribable.Name.replace(",", "").replace(" ", "_"), format, downloadPath, false)) {
            SubscriptionEntry entry = new SubscriptionEntry(newestSubscribable, true);
            entry.mLastUpdated = newestSubscribable.LastUpdated;
            user.setSubscriptionCacheEntry(newestSubscribable.ApiName, entry);
        }
    }

    try {
        tools = new JSONObject(new String(data));
        toolsArray = tools.getJSONArray("features");
        vesselNames = new ArrayList<>();
        adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_dropdown_item_1line, vesselNames);

        for (int i = 0; i < toolsArray.length(); i++) {
            JSONObject feature = toolsArray.getJSONObject(i);
            String vesselName = (feature.getJSONObject("properties").getString("vesselname") != null
                    && !feature.getJSONObject("properties").getString("vesselname").equals("null"))
                            ? feature.getJSONObject("properties").getString("vesselname")
                            : getString(R.string.vessel_name_unknown);
            List<Integer> toolsIdList = toolIdMap.get(vesselName) != null ? toolIdMap.get(vesselName)
                    : new ArrayList<Integer>();

            if (vesselName != null && !vesselNames.contains(vesselName)) {
                vesselNames.add(vesselName);
            }

            toolsIdList.add(i);
            toolIdMap.put(vesselName, toolsIdList);
        }

        inputField.setAdapter(adapter);
    } catch (JSONException e) {
        dialogInterface.getAlertDialog(getActivity(), R.string.search_tools_init_error,
                R.string.search_tools_init_info, -1).show();
        Log.e(TAG, "JSON parse error");
        e.printStackTrace();

        return;
    }

    if (searchToolsButton.getTag() != null) {
        inputField.requestFocus();
        inputField.setText(searchToolsButton.getTag().toString());
        inputField.selectAll();
    }

    inputField.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String selectedVesselName = ((TextView) view).getText().toString();
            List<Integer> selectedTools = toolIdMap.get(selectedVesselName);
            Gson gson = new Gson();
            String toolSetDateString;
            Date toolSetDate;

            rowsContainer.removeAllViews();

            for (int toolId : selectedTools) {
                JSONObject feature;
                Feature toolFeature;

                try {
                    feature = toolsArray.getJSONObject(toolId);

                    if (feature.getJSONObject("geometry").getString("type").equals("LineString")) {
                        toolFeature = gson.fromJson(feature.toString(), LineFeature.class);
                    } else {
                        toolFeature = gson.fromJson(feature.toString(), PointFeature.class);
                    }

                    toolSetDateString = toolFeature.properties.setupdatetime != null
                            ? toolFeature.properties.setupdatetime
                            : "2038-00-00T00:00:00";
                    toolSetDate = simpleDateFormat.parse(toolSetDateString);

                } catch (JSONException | ParseException e) {
                    dialogInterface.getAlertDialog(getActivity(), R.string.search_tools_init_error,
                            R.string.search_tools_init_info, -1).show();
                    e.printStackTrace();

                    return;
                }

                ToolSearchResultRow row = rowsInterface.getToolSearchResultRow(getActivity(),
                        R.drawable.ikon_kystfiske, toolFeature);
                long toolTime = System.currentTimeMillis() - toolSetDate.getTime();
                long highlightCutoff = ((long) getResources().getInteger(R.integer.milliseconds_in_a_day))
                        * ((long) getResources().getInteger(R.integer.days_to_highlight_active_tool));

                if (toolTime > highlightCutoff) {
                    int colorId = ContextCompat.getColor(getActivity(), R.color.error_red);
                    row.setDateTextViewTextColor(colorId);
                }

                rowsContainer.addView(row.getView());
            }

            viewInMapButton.setEnabled(true);
            inputField.setTag(selectedVesselName);
            searchToolsButton.setTag(selectedVesselName);
            jumpToBottomButton.setVisibility(View.VISIBLE);
            jumpToBottomButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new Handler().post(new Runnable() {
                        @Override
                        public void run() {
                            scrollView.scrollTo(0, rowsContainer.getBottom());
                        }
                    });
                }
            });

        }
    });

    viewInMapButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String vesselName = inputField.getTag().toString();
            highlightToolsInMap(vesselName);

            dialog.dismiss();
        }
    });

    dismissButton.setOnClickListener(onClickListenerInterface.getDismissDialogListener(dialog));
    dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
    dialog.show();
}

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

private void doDelete(Query post, HttpServletResponse response) throws IOException {

    String callback = post.get("callback", null);
    boolean jsonp = callback != null && callback.length() > 0;

    String id = post.get("id_str", "");
    if ("".equals(id)) {
        response.sendError(400, "your request must contain a `id_str` parameter.");
        return;//from w w w  . j  ava2 s  .com
    }

    String screen_name = post.get("screen_name", "");
    if ("".equals(screen_name)) {
        response.sendError(400, "your request must contain a `screen_name` parameter.");
        return;
    }

    ImportProfileEntry entry = DAO.SearchLocalImportProfiles(id);
    List<String> sharers = entry.getSharers();
    boolean sharerExists = sharers.remove(screen_name);
    entry.setSharers(sharers);
    boolean successful = false;
    if (sharerExists && DAO.writeImportProfile(entry, true)) {
        successful = true;
    } else {
        throw new IOException("Unable to delete import profile : " + entry.getId());
    }
    post.setResponse(response, "application/javascript");
    JSONObject json = new JSONObject(true);
    json.put("status", "ok");
    json.put("records", sharerExists && successful ? 1 : 0);
    json.put("message", "deleted");
    // write json
    response.setCharacterEncoding("UTF-8");
    PrintWriter sos = response.getWriter();
    if (jsonp)
        sos.print(callback + "(");
    sos.print(json.toString());
    if (jsonp)
        sos.println(");");
    sos.println();
}

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

private void doSearch(Query post, HttpServletResponse response) throws IOException {
    String callback = post.get("callback", "");
    boolean minified = post.get("minified", false);
    boolean jsonp = callback != null && callback.length() > 0;
    String source_type = post.get("source_type", "");
    String screen_name = post.get("screen_name", "");
    String msg_id = post.get("msg_id", "");
    String detailed = post.get("detailed", "");
    // source_type either has to be null a a valid SourceType value
    if (!"".equals(source_type) && !SourceType.isValid(source_type)) {
        response.sendError(400, "your request must contain a valid source_type parameter.");
        return;/*from   w  w  w .  ja  v a 2s .  c o m*/
    }
    Map<String, String> searchConstraints = new HashMap<>();
    if (!"".equals(source_type)) {
        searchConstraints.put("source_type", source_type);
    }
    if (!"".equals(screen_name)) {
        searchConstraints.put("sharers", screen_name);
    }
    if (!"".equals(msg_id)) {
        searchConstraints.put("imported", msg_id);
    }
    Collection<ImportProfileEntry> entries = DAO.SearchLocalImportProfilesWithConstraints(searchConstraints,
            true);
    JSONArray entries_to_map = new JSONArray();
    for (ImportProfileEntry entry : entries) {
        JSONObject entry_to_map = entry.toJSON();
        if ("true".equals(detailed)) {
            String query = "";
            for (String msgId : entry.getImported()) {
                query += "id:" + msgId + " ";
            }
            DAO.SearchLocalMessages search = new DAO.SearchLocalMessages(query, Timeline.Order.CREATED_AT, 0,
                    1000, 0);
            entry_to_map.put("imported",
                    search.timeline.toJSON(false, "search_metadata", "statuses").get("statuses"));
        }
        entries_to_map.put(entry_to_map);
    }
    post.setResponse(response, "application/javascript");

    JSONObject m = new JSONObject(true);
    JSONObject metadata = new JSONObject();
    metadata.put("count", entries.size());
    metadata.put("client", post.getClientHost());
    m.put("search_metadata", metadata);
    m.put("profiles", entries_to_map);

    // write json
    response.setCharacterEncoding("UTF-8");
    PrintWriter sos = response.getWriter();
    if (jsonp)
        sos.print(callback + "(");
    sos.print(minified ? m.toString() : m.toString(2));
    if (jsonp)
        sos.println(");");
    sos.println();
}

From source file:com.UAE.ibeaconreference.AppEngineClient.java

public static Response getOrPost(Request request) {
    mErrorMessage = null;/*from ww  w .  j  ava2 s . co  m*/
    HttpURLConnection conn = null;
    Response response = null;
    try {
        conn = (HttpURLConnection) request.uri.openConnection();
        //            if (!mAuthenticator.authenticate(conn)) {
        //                mErrorMessage = str(R.string.aerc_authentication_failed) + ": " + mAuthenticator.errorMessage();
        //            } else 
        {
            if (request.headers != null) {
                for (String header : request.headers.keySet()) {
                    for (String value : request.headers.get(header)) {
                        conn.addRequestProperty(header, value);
                    }
                }
            }
            if (request instanceof POST) {
                byte[] payload = ((POST) request).body;
                String s = new String(payload, "UTF-8");
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setRequestMethod("POST");

                JSONObject jsonobj = getJSONObject(s);

                conn.setRequestProperty("Content-Type", "application/json; charset=utf8");

                // ...

                OutputStream os = conn.getOutputStream();
                os.write(jsonobj.toString().getBytes("UTF-8"));
                os.close();

                //                    conn.setFixedLengthStreamingMode(payload.length);
                //                    conn.getOutputStream().write(payload);
                int status = conn.getResponseCode();
                if (status / 100 != 2)
                    response = new Response(status, new Hashtable<String, List<String>>(),
                            conn.getResponseMessage().getBytes());
            }
            if (response == null) {
                int a = conn.getResponseCode();
                if (a == 401) {
                    response = new Response(a, conn.getHeaderFields(), new byte[] {});
                }
                InputStream a1 = conn.getErrorStream();
                BufferedInputStream in = new BufferedInputStream(conn.getInputStream());

                byte[] body = readStream(in);

                response = new Response(conn.getResponseCode(), conn.getHeaderFields(), body);
                //   List<String> a = conn.getHeaderFields().get("aa");
            }
        }
    } catch (IOException e) {
        e.printStackTrace(System.err);
        mErrorMessage = ((request instanceof POST) ? "POST " : "GET ") + str(R.string.aerc_failed) + ": "
                + e.getLocalizedMessage();
    } finally {
        if (conn != null)
            conn.disconnect();
    }
    return response;
}

From source file:com.yanzhenjie.nohttp.HttpHeaders.java

@Override
public final String toJSONString() {
    JSONObject jsonObject = new JSONObject();
    Set<Map.Entry<String, List<String>>> entrySet = entrySet();
    for (Map.Entry<String, List<String>> entry : entrySet) {
        String key = entry.getKey();
        List<String> values = entry.getValue();
        JSONArray value = new JSONArray(values);
        try {/*from  w  w w  .  j  a va 2 s  .  c  o  m*/
            jsonObject.put(key, value);
        } catch (JSONException e) {
            Logger.w(e);
        }
    }

    return jsonObject.toString();
}

From source file:net.zorgblub.typhon.dto.PageOffsets.java

public String toJSON() throws JSONException {
    JSONObject jsonObject = new JSONObject();

    jsonObject.put(Fields.fontFamily.name(), this.fontFamily);
    jsonObject.put(Fields.fontSize.name(), this.fontSize);
    jsonObject.put(Fields.vMargin.name(), this.vMargin);
    jsonObject.put(Fields.hMargin.name(), this.hMargin);
    jsonObject.put(Fields.lineSpacing.name(), this.lineSpacing);
    jsonObject.put(Fields.fullScreen.name(), this.fullScreen);
    jsonObject.put(Fields.allowStyling.name(), this.allowStyling);
    jsonObject.put(Fields.algorithmVersion.name(), this.algorithmVersion);

    jsonObject.put(Fields.offsets.name(), new JSONArray(this.offsets));

    return jsonObject.toString();
}