Example usage for org.json JSONObject put

List of usage examples for org.json JSONObject put

Introduction

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

Prototype

public JSONObject put(String key, Object value) throws JSONException 

Source Link

Document

Put a key/value pair in the JSONObject.

Usage

From source file:com.swiftnav.sbp.tracking.TrackingChannelCorrelation.java

@Override
public JSONObject toJSON() {
    JSONObject obj = new JSONObject();
    obj.put("I", I);
    obj.put("Q", Q);
    return obj;//from   w  w  w. j  a  va2s . c om
}

From source file:it.unicaradio.android.tasks.SendSongRequestAsyncTask.java

/**
 * {@inheritDoc}//from   www.j  a  v  a 2  s  .  c  o m
 */
@Override
protected Response<String> doInBackground(Void... params) {
    JSONObject request = new JSONObject();
    try {
        request.put("method", "sendEmail");
        request.put("params", songRequest.toJSON(context));
    } catch (JSONException e) {
        return new Response<String>(Error.INTERNAL_GENERIC_ERROR);
    }

    String requestJSONString = request.toString();
    Log.d(TAG, MessageFormat.format("request: {0}", requestJSONString));

    byte[] postData = requestJSONString.getBytes();
    byte[] httpResult;
    try {
        httpResult = NetworkUtils.httpPost(WEB_SERVICE, postData, "application/json");
    } catch (ClientProtocolException e1) {
        return new Response<String>(Error.INTERNAL_GENERIC_ERROR);
    } catch (IOException e1) {
        return new Response<String>(Error.INTERNAL_DOWNLOAD_ERROR);
    } catch (HttpException e1) {
        return new Response<String>(Error.INTERNAL_GENERIC_ERROR);
    }

    if (httpResult == null) {
        return new Response<String>(Error.INTERNAL_GENERIC_ERROR);
    }

    String httpResultString = new String(httpResult);
    Log.d(TAG, MessageFormat.format("response: {0}", httpResultString));
    try {
        JSONObject response = new JSONObject(httpResultString);
        int errorCodeInt = response.getInt("errorCode");
        Error errorCode = Error.fromInteger(errorCodeInt);
        if (errorCode == Error.NO_ERROR) {
            return new Response<String>(httpResultString);
        } else {
            return new Response<String>(errorCode);
        }
    } catch (JSONException e) {
        return new Response<String>(Error.INTERNAL_GENERIC_ERROR);
    }
}

From source file:edu.stanford.junction.test.multiconnect.Sender.java

@Override
public void onActivityJoin() {
    //new Thread() {
    //   public void run() {
    try {//from w w  w  .  j a v  a2 s.  com
        int tic = 0;
        JSONObject msg = new JSONObject();
        while (tic < 5) {
            msg.put("tic", tic++);
            sendMessageToRole("receiver", msg);
            Thread.sleep(3000);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    //   }
    //}.start();
}

From source file:org.b3log.solo.api.metaweblog.MetaWeblogAPI.java

/**
 * MetaWeblog requests processing./*from  www  . j av  a 2  s .c  o  m*/
 * 
 * @param request the specified http servlet request
 * @param response the specified http servlet response
 * @param context the specified http request context
 */
@RequestProcessing(value = "/apis/metaweblog", method = HTTPRequestMethod.POST)
public void metaWeblog(final HttpServletRequest request, final HttpServletResponse response,
        final HTTPRequestContext context) {
    final TextXMLRenderer renderer = new TextXMLRenderer();
    context.setRenderer(renderer);

    String responseContent = null;
    try {
        final ServletInputStream inputStream = request.getInputStream();
        final String xml = IOUtils.toString(inputStream, "UTF-8");
        final JSONObject requestJSONObject = XML.toJSONObject(xml);

        final JSONObject methodCall = requestJSONObject.getJSONObject(METHOD_CALL);
        final String methodName = methodCall.getString(METHOD_NAME);
        LOGGER.log(Level.INFO, "MetaWeblog[methodName={0}]", methodName);

        final JSONArray params = methodCall.getJSONObject("params").getJSONArray("param");

        if (METHOD_DELETE_POST.equals(methodName)) {
            params.remove(0); // Removes the first argument "appkey"
        }

        final String userEmail = params.getJSONObject(INDEX_USER_EMAIL).getJSONObject("value")
                .getString("string");
        final JSONObject user = userQueryService.getUserByEmail(userEmail);
        if (null == user) {
            throw new Exception("No user[email=" + userEmail + "]");
        }

        final String userPwd = params.getJSONObject(INDEX_USER_PWD).getJSONObject("value").getString("string");
        if (!user.getString(User.USER_PASSWORD).equals(userPwd)) {
            throw new Exception("Wrong password");
        }

        if (METHOD_GET_USERS_BLOGS.equals(methodName)) {
            responseContent = getUsersBlogs();
        } else if (METHOD_GET_CATEGORIES.equals(methodName)) {
            responseContent = getCategories();
        } else if (METHOD_GET_RECENT_POSTS.equals(methodName)) {
            final int numOfPosts = params.getJSONObject(INDEX_NUM_OF_POSTS).getJSONObject("value")
                    .getInt("int");
            responseContent = getRecentPosts(numOfPosts);
        } else if (METHOD_NEW_POST.equals(methodName)) {
            final JSONObject article = parsetPost(methodCall);
            article.put(Article.ARTICLE_AUTHOR_EMAIL, userEmail);
            addArticle(article);

            final StringBuilder stringBuilder = new StringBuilder(
                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse><params><param><value><string>")
                            .append(article.getString(Keys.OBJECT_ID))
                            .append("</string></value></param></params></methodResponse>");
            responseContent = stringBuilder.toString();
        } else if (METHOD_GET_POST.equals(methodName)) {
            final String postId = params.getJSONObject(INDEX_POST_ID).getJSONObject("value")
                    .getString("string");
            responseContent = getPost(postId);
        } else if (METHOD_EDIT_POST.equals(methodName)) {
            final JSONObject article = parsetPost(methodCall);
            final String postId = params.getJSONObject(INDEX_POST_ID).getJSONObject("value")
                    .getString("string");
            article.put(Keys.OBJECT_ID, postId);

            article.put(Article.ARTICLE_AUTHOR_EMAIL, userEmail);
            final JSONObject updateArticleRequest = new JSONObject();
            updateArticleRequest.put(Article.ARTICLE, article);
            articleMgmtService.updateArticle(updateArticleRequest);

            final StringBuilder stringBuilder = new StringBuilder(
                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse><params><param><value><string>")
                            .append(postId).append("</string></value></param></params></methodResponse>");
            responseContent = stringBuilder.toString();
        } else if (METHOD_DELETE_POST.equals(methodName)) {
            final String postId = params.getJSONObject(INDEX_POST_ID).getJSONObject("value")
                    .getString("string");
            articleMgmtService.removeArticle(postId);

            final StringBuilder stringBuilder = new StringBuilder(
                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse><params><param><value><boolean>")
                            .append(true).append("</boolean></value></param></params></methodResponse>");
            responseContent = stringBuilder.toString();
        } else {
            throw new UnsupportedOperationException("Unsupported method[name=" + methodName + "]");
        }
    } catch (final Exception e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);

        responseContent = "";
        final StringBuilder stringBuilder = new StringBuilder(
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse><fault><value><struct>")
                        .append("<member><name>faultCode</name><value><int>500</int></value></member>")
                        .append("<member><name>faultString</name><value><string>").append(e.getMessage())
                        .append("</string></value></member></struct></value></fault></methodResponse>");
        responseContent = stringBuilder.toString();
    }

    renderer.setContent(responseContent);
}

From source file:org.b3log.solo.api.metaweblog.MetaWeblogAPI.java

/**
 * Parses the specified method call for an article.
 * /*from   www.  ja v a 2s .co  m*/
 * @param methodCall the specified method call
 * @return article
 * @throws Exception exception 
 */
private JSONObject parsetPost(final JSONObject methodCall) throws Exception {
    final JSONObject ret = new JSONObject();

    final JSONArray params = methodCall.getJSONObject("params").getJSONArray("param");
    final JSONObject post = params.getJSONObject(INDEX_POST).getJSONObject("value").getJSONObject("struct");
    final JSONArray members = post.getJSONArray("member");

    for (int i = 0; i < members.length(); i++) {
        final JSONObject member = members.getJSONObject(i);
        final String name = member.getString("name");

        if ("dateCreated".equals(name)) {
            final JSONObject preference = preferenceQueryService.getPreference();

            final String dateString = member.getJSONObject("value").getString("dateTime.iso8601");
            Date date = null;
            try {
                date = (Date) DateFormatUtils.ISO_DATETIME_FORMAT.parseObject(dateString);
            } catch (final ParseException e) {
                LOGGER.log(Level.WARNING,
                        "Parses article create date failed with ISO8601, retry to parse with pattern[yyyy-MM-dd'T'HH:mm:ss]");
                final String timeZoneId = preference.getString(Preference.TIME_ZONE_ID);
                final TimeZone timeZone = TimeZone.getTimeZone(timeZoneId);
                final DateFormat format = new SimpleDateFormat("yyyyMMdd'T'HH:mm:ss");
                format.setTimeZone(timeZone);
                date = format.parse(dateString);
            }
            ret.put(Article.ARTICLE_CREATE_DATE, date);
        } else if ("title".equals(name)) {
            ret.put(Article.ARTICLE_TITLE, member.getJSONObject("value").getString("string"));
        } else if ("description".equals(name)) {
            final String content = member.getJSONObject("value").getString("string");
            ret.put(Article.ARTICLE_CONTENT, content);

            final String plainTextContent = Jsoup.parse(content).text();
            if (plainTextContent.length() > ARTICLE_ABSTRACT_LENGTH) {
                ret.put(Article.ARTICLE_ABSTRACT, plainTextContent.substring(0, ARTICLE_ABSTRACT_LENGTH));
            } else {
                ret.put(Article.ARTICLE_ABSTRACT, plainTextContent);
            }
        } else if ("categories".equals(name)) {
            final StringBuilder tagBuilder = new StringBuilder();

            final JSONObject data = member.getJSONObject("value").getJSONObject("array").getJSONObject("data");
            if (0 == data.length()) {
                throw new Exception("At least one Tag");
            }

            final Object value = data.get("value");
            if (value instanceof JSONArray) {
                final JSONArray tags = (JSONArray) value;
                for (int j = 0; j < tags.length(); j++) {
                    final String tagTitle = tags.getJSONObject(j).getString("string");
                    tagBuilder.append(tagTitle);

                    if (j < tags.length() - 1) {
                        tagBuilder.append(",");
                    }
                }
            } else {
                final JSONObject tag = (JSONObject) value;
                tagBuilder.append(tag.getString("string"));
            }

            ret.put(Article.ARTICLE_TAGS_REF, tagBuilder.toString());
        }
    }

    final boolean publish = 1 == params.getJSONObject(INDEX_PUBLISH).getJSONObject("value").getInt("boolean")
            ? true
            : false;
    ret.put(Article.ARTICLE_IS_PUBLISHED, publish);

    ret.put(Article.ARTICLE_COMMENTABLE, true);
    ret.put(Article.ARTICLE_VIEW_PWD, "");

    return ret;
}

From source file:org.wso2.emm.agent.services.DeviceStartupIntentReceiver.java

/**
 * Initiates device notifier on device startup.
 * @param context - Application context.
 *//*from w  w w .j  av  a2 s. co m*/
private void setRecurringAlarm(Context context) {
    this.resources = context.getApplicationContext().getResources();
    String mode = Preference.getString(context, Constants.PreferenceFlag.NOTIFIER_TYPE);
    boolean isLocked = Preference.getBoolean(context, Constants.IS_LOCKED);
    String lockMessage = Preference.getString(context, Constants.LOCK_MESSAGE);

    if (lockMessage == null || lockMessage.isEmpty()) {
        lockMessage = resources.getString(R.string.txt_lock_activity);
    }

    if (isLocked) {
        Operation lockOperation = new Operation();
        lockOperation.setId(DEFAULT_ID);
        lockOperation.setCode(Constants.Operation.DEVICE_LOCK);
        try {
            JSONObject payload = new JSONObject();
            payload.put(Constants.ADMIN_MESSAGE, lockMessage);
            payload.put(Constants.IS_HARD_LOCK_ENABLED, true);
            lockOperation.setPayLoad(payload.toString());
            OperationProcessor operationProcessor = new OperationProcessor(context);
            operationProcessor.doTask(lockOperation);
        } catch (AndroidAgentException e) {
            Log.e(TAG, "Error occurred while executing hard lock operation at the device startup");
        } catch (JSONException e) {
            Log.e(TAG, "Error occurred while building hard lock operation payload");
        }
    }

    int interval = Preference.getInt(context, context.getResources().getString(R.string.shared_pref_frequency));
    if (interval == DEFAULT_INDEX) {
        interval = DEFAULT_INTERVAL;
    }

    if (mode == null) {
        mode = Constants.NOTIFIER_LOCAL;
    }

    if (Preference.getBoolean(context, Constants.PreferenceFlag.REGISTERED)
            && Constants.NOTIFIER_LOCAL.equals(mode.trim().toUpperCase(Locale.ENGLISH))) {
        long startTime = DEFAULT_TIME_MILLISECONDS;

        Intent alarmIntent = new Intent(context, AlarmReceiver.class);
        PendingIntent recurringAlarmIntent = PendingIntent.getBroadcast(context, DEFAULT_REQUEST_CODE,
                alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, startTime, interval,
                recurringAlarmIntent);
        Log.d(TAG, "Setting up alarm manager for polling every " + interval + " milliseconds.");
    }
}

From source file:org.loklak.harvester.YoutubeScraper.java

public static JSONObject parseVideo(final BufferedReader br) throws IOException {
    String input;// ww  w  .  j  a  v a2  s.  c  om
    JSONObject json = new JSONObject(true);
    boolean parse_span = false, parse_license = false;
    String itemprop = "", itemtype = ""; // values for span
    while ((input = br.readLine()) != null)
        try {
            input = input.trim();
            //System.out.println(input); // uncomment temporary to debug or add new fields
            int p;

            if (parse_license) {
                if ((p = input.indexOf("<li")) >= 0) {
                    String tag = parseTag(input, p);
                    if (tag == null)
                        continue;
                    if (tag.startsWith("<a ")) {
                        tag = parseTag(tag, 0);
                        addRDF(new String[] { "youtube", "category", tag }, json);
                    } else {
                        addRDF(new String[] { "youtube", "license", tag }, json);
                    }
                    parse_license = false;
                    continue;
                }
            } else if (parse_span) {
                if ((p = input.indexOf("itemprop=\"")) >= 0) {
                    String[] token = parseItemprop(input, p, new String[] { "href", "content" }, "");
                    if (token == null)
                        continue;
                    int q = itemtype.indexOf("//");
                    if (q < 0)
                        continue;
                    String subject = itemtype.substring(q + 2).replace('.', '_').replace('/', '_');
                    String predicate = itemprop + "_" + token[1];
                    String object = token[2];
                    addRDF(new String[] { subject, predicate, object }, json);
                    continue;
                }
                if (input.indexOf("</span>") >= 0) {
                    parse_span = false;
                    continue;
                }
            } else {
                tags: for (String tag : html_tags) {
                    if ((p = input.indexOf("<" + tag)) >= 0) {
                        addRDF(new String[] { "html", tag, parseTag(input, p) }, json);
                        continue tags;
                    }
                }
                vocs: for (String subject : microformat_vocabularies) {
                    if ((p = input.indexOf("property=\"" + subject + ":")) >= 0) {
                        addRDF(parseMicroformat(input, "property", p), json);
                        continue vocs;
                    }
                    if ((p = input.indexOf("name=\"" + subject + ":")) >= 0) {
                        addRDF(parseMicroformat(input, "name", p), json);
                        continue vocs;
                    }
                }
                if ((p = input.indexOf("span itemprop=\"")) >= 0) {
                    String[] token = parseItemprop(input, p, new String[] { "itemtype" }, "");
                    if (token == null)
                        continue;
                    itemprop = token[1];
                    itemtype = token[2];
                    parse_span = true;
                    continue;
                }
                if ((p = input.indexOf("itemprop=\"")) >= 0) {
                    String[] token = parseItemprop(input, p, new String[] { "content" }, "youtube");
                    if (token == null)
                        continue;
                    addRDF(token, json);
                    continue;
                }
                if ((p = input.indexOf("class=\"content watch-info-tag-list")) >= 0) {
                    parse_license = true;
                    continue;
                }
                if ((p = input.indexOf("yt-subscriber-count")) >= 0) {
                    String subscriber_string = parseProp(input, p, "title");
                    if (subscriber_string == null)
                        continue;
                    json.put("youtube_subscriber", parseNumber(subscriber_string));
                    continue;
                }
                if (input.indexOf("\"like this") > 0 && (p = input.indexOf("yt-uix-button-content")) >= 0) {
                    String likes_string = parseTag(input, p);
                    json.put("youtube_likes", parseNumber(likes_string));
                    continue;
                }
                if (input.indexOf("\"dislike this") > 0 && (p = input.indexOf("yt-uix-button-content")) >= 0) {
                    String dislikes_string = parseTag(input, p);
                    json.put("youtube_dislikes", parseNumber(dislikes_string));
                    continue;
                }
                if ((p = input.indexOf("watch-view-count")) >= 0) {
                    String viewcount_string = parseTag(input, p);
                    if (viewcount_string == null)
                        continue;
                    viewcount_string = viewcount_string.replace(" views", "");
                    if (viewcount_string.length() == 0)
                        continue;
                    long viewcount = 0;
                    // if there are no views, there may be a string saying "No". But this is done in all languages, so we just catch a NumberFormatException
                    try {
                        viewcount = parseNumber(viewcount_string);
                    } catch (NumberFormatException e) {
                    }
                    json.put("youtube_viewcount", viewcount);
                    continue;
                }
                if ((p = input.indexOf("watch?v=")) >= 0) {
                    p += 8;
                    int q = input.indexOf("\"", p);
                    if (q > 0) {
                        String videoid = input.substring(p, q);
                        int r = videoid.indexOf('&');
                        if (r > 0)
                            videoid = videoid.substring(0, r);
                        addRDF(new String[] { "youtube", "next", videoid }, json);
                        continue;
                    }
                }
                if ((p = input.indexOf("playlist-header-content")) >= 0) {
                    String playlist_title = parseProp(input, p, "data-list-title");
                    if (playlist_title == null)
                        continue;
                    addRDF(new String[] { "youtube", "playlist_title", playlist_title }, json);
                    continue;
                }
                if ((p = input.indexOf("yt-uix-scroller-scroll-unit")) >= 0) {
                    String playlist_videoid = parseProp(input, p, "data-video-id");
                    if (playlist_videoid == null)
                        continue;
                    addRDF(new String[] { "youtube", "playlist_videoid", playlist_videoid }, json);
                    continue;
                }
                if ((p = input.indexOf("watch-description-text")) >= 0) {
                    p = input.indexOf('>', p);
                    int q = input.indexOf("</div", p);
                    String text = input.substring(p + 1, q < 0 ? input.length() : q);
                    text = paragraph.matcher(brend.matcher(text).replaceAll("\n")).replaceAll("").trim();
                    Matcher m;
                    anchor_loop: while ((m = anchor_pattern.matcher(text)).find())
                        try {
                            text = m.replaceFirst(m.group(1) + " ");
                        } catch (IllegalArgumentException e) {
                            text = "";
                            break anchor_loop;
                        }
                    text = CharacterCoding.html2unicode(text);
                    json.put("youtube_description", text);
                    continue;
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
            System.err.println("error in video " + json.toString(2));
            System.err.println("current line: " + input);
            System.exit(0);
        }
    br.close();
    return json;
}

From source file:org.loklak.harvester.YoutubeScraper.java

private static void addRDF(String[] spo, JSONObject json) {
    if (spo == null)
        return;/*from w  w w  . j a va  2  s. co m*/
    String subject = spo[0];
    String predicate = spo[1];
    String object = CharacterCoding.html2unicode(spo[2]);
    if (subject.length() == 0 || predicate.length() == 0 || object.length() == 0)
        return;
    String key = subject + "_" + predicate;
    JSONArray objects = null;
    try {
        objects = json.getJSONArray(key);
    } catch (JSONException e) {
        objects = new JSONArray();
        json.put(key, objects);
    }
    // double-check (wtf why is ths that complex?)
    for (Object o : objects) {
        if (o instanceof String && ((String) o).equals(object))
            return;
    }
    // add the object to the objects
    objects.put(object);
}

From source file:io.selendroid.server.FindElementHandlerTest.java

public void assertThatFindElementResponseHasCorrectFormat() throws Exception {
    HttpResponse response = executeCreateSessionRequest();
    SelendroidAssert.assertResponseIsRedirect(response);
    JSONObject session = parseJsonResponse(response);
    String sessionId = session.getString("sessionId");
    Assert.assertFalse(sessionId.isEmpty());

    JSONObject payload = new JSONObject();
    payload.put("using", "id");
    payload.put("value", "my_button_bar");

    String url = "http://" + host + ":" + port + "/wd/hub/session/" + sessionId + "/element";
    HttpResponse element = executeRequestWithPayload(url, HttpMethod.POST, payload.toString());
    SelendroidAssert.assertResponseIsOk(element);
}

From source file:de.dmxcontrol.programmer.EntityProgrammer.java

public static void Clear(EntityProgrammer programmer) throws JSONException {
    if (programmer == null) {
        return;/*  w w  w  . java  2 s.c  o  m*/
    }
    JSONObject o = new JSONObject();
    o.put("Type", NetworkID);
    o.put("GUID", programmer.guid);
    o.put("Clear", true);

    ServiceFrontend.get().sendMessage(o.toString().getBytes());
    o = null;
    if (o == null) {
        programmer.states.clear();
        programmer.runChangeListener();
    }
    return;
}