Example usage for org.json JSONObject JSONObject

List of usage examples for org.json JSONObject JSONObject

Introduction

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

Prototype

public JSONObject(String source) throws JSONException 

Source Link

Document

Construct a JSONObject from a source JSON text string.

Usage

From source file:org.everit.osgi.webconsole.configuration.ConfigServlet.java

@Override
protected void doPut(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    String requestBody = requestBody(req);
    String pid = req.getParameter("pid");
    String factoryPid = req.getParameter("factoryPid");
    String configAdminPid = req.getParameter("configAdminPid");
    String location = req.getParameter("location");
    Map<String, List<String>> attributes = extractRawAttributesFromJSON(new JSONObject(requestBody));
    if (pid == null) {
        resp.setContentType("application/json");
        JSONWriter writer = new JSONWriter(resp.getWriter());
        configManager.createConfiguration(configAdminPid, factoryPid, location, attributes).toJSON(writer);

    } else {//  ww w  .  j  a  va 2  s  .  co  m
        configManager.updateConfiguration(configAdminPid, pid, factoryPid, attributes);
        printSuccess(resp);
    }
}

From source file:org.achtern.AchternEngine.core.resource.loader.json.JsonLoader.java

/**
 * Constructs the {@link org.json.JSONObject} and parses it.
 * This performs any type of loading and parsing.
 * This should load the resource, but should not constructed it,
 * just loading/parsing and preparations to create the object
 * @param name The name of the original file
 * @param input The input file/*from ww w  . j  av  a  2 s . com*/
 * @throws LoadingException when the loading fails
 */
@Override
public void load(String name, String input) throws LoadingException {
    try {
        jsonObject = new JSONObject(input);
    } catch (JSONException e) {
        throw new LoadingException("Failed to parse json.", e);
    }
}

From source file:net.cellcloud.talk.HttpDialogueHandler.java

@Override
protected void doPost(HttpRequest request, HttpResponse response) throws IOException {
    HttpSession session = request.getSession();
    if (null != session) {
        try {//from w  w  w.  ja va  2  s.  co  m
            // ??
            JSONObject json = new JSONObject(new String(request.readRequestData(), Charset.forName("UTF-8")));
            // ? JSON ?
            String speakerTag = json.getString(Tag);
            String celletIdentifier = json.getString(Identifier);
            JSONObject primitiveJSON = json.getJSONObject(Primitive);
            // ?
            Primitive primitive = new Primitive(speakerTag);
            PrimitiveSerializer.read(primitive, primitiveJSON);
            // ?
            this.talkService.processDialogue(session, speakerTag, celletIdentifier, primitive);

            // ?
            // FIXME 2014/10/03 ??
            JSONObject responseData = new JSONObject();

            // ??
            Queue<Message> queue = session.getQueue();
            if (!queue.isEmpty()) {
                ArrayList<String> identifiers = new ArrayList<String>(queue.size());
                ArrayList<Primitive> primitives = new ArrayList<Primitive>(queue.size());
                for (int i = 0, size = queue.size(); i < size; ++i) {
                    // ?
                    Message message = queue.poll();
                    // 
                    Packet packet = Packet.unpack(message.get());
                    if (null != packet) {
                        // ? cellet identifier
                        byte[] identifier = packet.getSubsegment(1);

                        // ?????
                        byte[] primData = packet.getSubsegment(0);
                        ByteArrayInputStream stream = new ByteArrayInputStream(primData);

                        // ???
                        Primitive prim = new Primitive(Nucleus.getInstance().getTagAsString());
                        prim.read(stream);

                        // 
                        identifiers.add(Utils.bytes2String(identifier));
                        primitives.add(prim);
                    }
                }

                // ?
                JSONArray jsonPrimitives = this.convert(identifiers, primitives);
                responseData.put(Primitives, jsonPrimitives);
            }

            // ?
            responseData.put(Queue, queue.size());

            // ?
            this.respondWithOk(response, responseData);
        } catch (JSONException e) {
            Logger.log(HttpDialogueHandler.class, e, LogLevel.ERROR);
            this.respond(response, HttpResponse.SC_BAD_REQUEST);
        }
    } else {
        this.respond(response, HttpResponse.SC_UNAUTHORIZED);
    }
}

From source file:it.mb.whatshare.SendToGCMActivity.java

/**
 * Loads the ID and name of the paired device in use to share content when
 * Whatsapp is not installed on this device.
 * /*w ww . java2 s .  co m*/
 * @param activity
 *            the calling activity
 * @return the device loaded from file if any is configured,
 *         <code>null</code> otherwise
 * @throws OptionalDataException
 * @throws ClassNotFoundException
 * @throws IOException
 */
static Pair<PairedDevice, String> loadOutboundPairing(Context activity)
        throws OptionalDataException, ClassNotFoundException, IOException {
    FileInputStream fis = activity.openFileInput("pairing");
    Scanner scanner = new Scanner(fis).useDelimiter("\\Z");
    JSONObject json;
    try {
        json = new JSONObject(scanner.next());
        String name = json.getString("name");
        String type = json.getString("type");
        String assignedID = json.getString("assignedID");
        return new Pair<PairedDevice, String>(new PairedDevice(assignedID, name, type), assignedID);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.travis4j.rest.JsonResponse.java

public JSONObject getJson() throws JSONException {
    return new JSONObject(getBody());
}

From source file:nl.spellenclubeindhoven.dominionshuffle.Application.java

public void loadResult() {
    try {// w w  w . j a  v a2s  .  c om
        JSONObject jsonResult = new JSONObject(DataReader.readStringFromFile(this, "result.json"));

        JSONArray jsonCards = jsonResult.getJSONArray("cards");
        LinkedList<Card> cards = new LinkedList<Card>();

        for (int i = 0; i < jsonCards.length(); i++) {
            Card card = dataReader.getData().getCard(jsonCards.getString(i));
            if (card == null)
                return;
            cards.add(card);
        }

        Card baneCard = null;
        Card obeliskCard = null;
        if (jsonResult.has("baneCard")) {
            baneCard = dataReader.getData().getCard(jsonResult.getString("baneCard"));
        }
        if (jsonResult.has("obeliskCard")) {
            obeliskCard = dataReader.getData().getCard(jsonResult.getString("obeliskCard"));
        }

        result = new Result();
        result.setCards(cards);
        result.setBaneCard(baneCard);
        result.setObeliskCard(obeliskCard);
    } catch (JSONException ignore) {
        ignore.printStackTrace();
    }
}

From source file:com.atinternet.tracker.Builder.java

/**
 * Prepare the hit queryString/*from ww  w  .jav a  2  s. co  m*/
 *
 * @return LinkedHashMap
 */
private LinkedHashMap<String, Object[]> prepareQuery() {
    LinkedHashMap<String, Object[]> formattedParameters = new LinkedHashMap<String, Object[]>();

    ArrayList<Param> completeBuffer = new ArrayList<Param>() {
        {
            addAll(persistentParams);
            addAll(volatileParams);
        }
    };

    ArrayList<Param> params = organizeParameters(completeBuffer);

    for (Param p : params) {
        String value = p.getValue().execute();
        String key = p.getKey();

        HashMap<String, String> plugins = PluginParam.get(tracker);
        if (plugins.containsKey(key)) {
            String pluginClass = plugins.get(key);
            Plugin plugin = null;
            try {
                plugin = (Plugin) Class.forName(pluginClass).newInstance();
                plugin.execute(tracker);
                value = plugin.getResponse();
                p.setType(Param.Type.JSON);
                key = Hit.HitParam.JSON.stringValue();
            } catch (Exception e) {
                e.printStackTrace();
                value = null;
            }
        } else if (key.equals(Hit.HitParam.UserId.stringValue())) {
            if (TechnicalContext.doNotTrackEnabled(Tracker.getAppContext())) {
                value = OPT_OUT;
            } else if (((Boolean) configuration.get(TrackerConfigurationKeys.HASH_USER_ID))) {
                value = Tool.SHA_256(value);
            }
        }

        if (p.getType() == Param.Type.Closure && Tool.parseJSON(value) != null) {
            p.setType(Param.Type.JSON);
        }

        if (value != null) {
            // Referrer processing
            if (key.equals(Hit.HitParam.Referrer.stringValue())) {

                value = value.replace("&", "$").replaceAll("[<>]", "");
            }

            if (p.getOptions() != null && p.getOptions().isEncode()) {
                value = Tool.percentEncode(value);
                p.getOptions().setSeparator(Tool.percentEncode(p.getOptions().getSeparator()));
            }
            int duplicateParamIndex = -1;
            String duplicateParamKey = null;

            Set<String> keys = formattedParameters.keySet();

            String[] keySet = keys.toArray(new String[keys.size()]);
            int length = keySet.length;
            for (int i = 0; i < length; i++) {
                if (keySet[i].equals(key)) {
                    duplicateParamIndex = i;
                    duplicateParamKey = key;
                    break;
                }
            }

            if (duplicateParamIndex != -1) {
                List<Object[]> values = new ArrayList<Object[]>(formattedParameters.values());
                Param duplicateParam = (Param) values.get(duplicateParamIndex)[0];
                String str = ((String) formattedParameters.get(duplicateParamKey)[1]).split("=")[0] + "=";
                String val = ((String) formattedParameters.get(duplicateParamKey)[1]).split("=")[1];

                if (p.getType() == Param.Type.JSON) {
                    Object json = Tool.parseJSON(Tool.percentDecode(val));
                    Object newJson = Tool.parseJSON(Tool.percentDecode(value));

                    if (json != null && json instanceof JSONObject) {
                        Map dictionary = Tool.toMap((JSONObject) json);

                        if (newJson instanceof JSONObject) {
                            Map newDictionary = Tool.toMap((JSONObject) newJson);
                            dictionary.putAll(newDictionary);

                            JSONObject jsonData = new JSONObject(dictionary);
                            formattedParameters.put(key, new Object[] { duplicateParam,
                                    makeSubQuery(key, Tool.percentEncode(jsonData.toString())) });
                        } else {
                            Tool.executeCallback(tracker.getListener(), CallbackType.warning,
                                    "Couldn't append value to a dictionary");
                        }
                    } else if (json != null && json instanceof JSONArray) {
                        try {
                            ArrayList<Object> array = new ArrayList<Object>();
                            JSONArray jArray = (JSONArray) json;
                            for (int i = 0; i < jArray.length(); i++) {
                                array.add(jArray.get(i).toString());
                            }
                            if (newJson instanceof JSONArray) {
                                jArray = (JSONArray) newJson;
                                for (int i = 0; i < jArray.length(); i++) {
                                    array.add(jArray.get(i).toString());
                                }
                                JSONObject jsonData = new JSONObject(array.toString());
                                formattedParameters.put(key, new Object[] { duplicateParam,
                                        makeSubQuery(key, Tool.percentEncode(jsonData.toString())) });
                            } else {
                                Tool.executeCallback(tracker.getListener(), CallbackType.warning,
                                        "Couldn't append value to an array");
                            }
                        } catch (JSONException e) {
                            Tool.executeCallback(tracker.getListener(), CallbackType.warning,
                                    "Couldn't append value to an array");
                        }
                    } else {
                        Tool.executeCallback(tracker.getListener(), CallbackType.warning,
                                "Couldn't append value to a JSON Object");
                    }
                } else if (duplicateParam.getType() == Param.Type.JSON) {
                    Tool.executeCallback(tracker.getListener(), CallbackType.warning,
                            "Couldn't append value to a JSON Object");
                } else {
                    formattedParameters.put(key,
                            new Object[] { duplicateParam, str + val + p.getOptions().getSeparator() + value });
                }
            } else {
                formattedParameters.put(key, new Object[] { p, makeSubQuery(key, value) });
            }
        }
    }
    return formattedParameters;
}

From source file:net.mandaria.radioreddit.apis.RadioRedditAPI.java

public static RadioStreams GetStreams(Context context, RadioRedditApplication application) {
    RadioStreams radiostreams = new RadioStreams();
    radiostreams.ErrorMessage = "";
    radiostreams.RadioStreams = new ArrayList<RadioStream>();

    try {//from  w w  w .j a  va2s .  c  om
        String url = context.getString(R.string.radio_reddit_streams);
        String outputStreams = "";
        boolean errorGettingStreams = false;

        try {
            outputStreams = HTTPUtil.get(context, url);
        } catch (Exception ex) {
            errorGettingStreams = true;
            radiostreams.ErrorMessage = context.getString(R.string.error_RadioRedditServerIsDownNotification);
            application.radioRedditIsDownErrorMessage = radiostreams.ErrorMessage;
            application.isRadioRedditDown = true;
        }

        if (!errorGettingStreams && outputStreams.length() > 0) {
            JSONTokener tokener = new JSONTokener(outputStreams);
            JSONObject json = new JSONObject(tokener);

            JSONObject streams = json.getJSONObject("streams");
            JSONArray streams_names = streams.names();
            ArrayList<RadioStream> list_radiostreams = new ArrayList<RadioStream>();

            // loop through each stream
            for (int i = 0; i < streams.length(); i++) {
                String name = streams_names.getString(i);
                JSONObject stream = streams.getJSONObject(name);

                RadioStream radiostream = new RadioStream();
                radiostream.Name = name;
                // if(stream.has("type"))
                radiostream.Type = stream.getString("type");
                radiostream.Description = stream.getString("description");
                radiostream.Status = stream.getString("status");

                // call status.json to get Relay
                // form url radioreddit.com + status + json
                String status_url = context.getString(R.string.radio_reddit_base_url) + radiostream.Status
                        + context.getString(R.string.radio_reddit_status);

                String outputStatus = "";
                boolean errorGettingStatus = false;

                try {
                    outputStatus = HTTPUtil.get(context, status_url);
                } catch (Exception ex) {
                    errorGettingStatus = true;
                    radiostreams.ErrorMessage = context
                            .getString(R.string.error_RadioRedditServerIsDownNotification);
                }

                //Log.e("RadioReddit", "Length of output: "+ outputStatus.length() + "; Content of output: " + outputStatus);
                // TODO: does  outputStatus.length() > 0 need to be checked here and return a ErrorMessage back and set ErrorGettingStatus = true? 

                if (!errorGettingStatus && outputStatus.length() > 0) {
                    JSONTokener status_tokener = new JSONTokener(outputStatus);
                    JSONObject status_json = new JSONObject(status_tokener);

                    radiostream.Online = Boolean.parseBoolean(status_json.getString("online").toLowerCase());

                    if (radiostream.Online == true) // if offline, no other nodes are available
                    {
                        radiostream.Relay = status_json.getString("relay");

                        list_radiostreams.add(radiostream);
                    }
                }
            }

            // JSON parsing reverses the list for some reason, fixing it...
            if (list_radiostreams.size() > 0) {
                // Sorting will happen later on select station activity
                //Collections.reverse(list_radiostreams);

                radiostreams.RadioStreams = list_radiostreams;
                application.isRadioRedditDown = false;
            } else {
                radiostreams.ErrorMessage = context.getString(R.string.error_NoStreams);
                application.radioRedditIsDownErrorMessage = radiostreams.ErrorMessage;
                application.isRadioRedditDown = true;
            }
        }
    } catch (Exception ex) {
        // We fail to get the streams...
        CustomExceptionHandler ceh = new CustomExceptionHandler(context);
        ceh.sendEmail(ex);

        radiostreams.ErrorMessage = ex.toString();
        ex.printStackTrace();
    }

    return radiostreams;
}

From source file:net.mandaria.radioreddit.apis.RadioRedditAPI.java

public static RadioSong GetCurrentSongInformation(Context context, RadioRedditApplication application) {
    RadioSong radiosong = new RadioSong();
    radiosong.ErrorMessage = "";

    try {/* w ww.  j  a v  a  2s.c  o m*/
        String status_url = context.getString(R.string.radio_reddit_base_url) + application.CurrentStream.Status
                + context.getString(R.string.radio_reddit_status);

        String outputStatus = "";
        boolean errorGettingStatus = false;

        try {
            outputStatus = HTTPUtil.get(context, status_url);
        } catch (Exception ex) {
            ex.printStackTrace();
            errorGettingStatus = true;
            // For now, not used. It is acceptable to error out and not alert the user
            // radiosong.ErrorMessage = context.getString(R.string.error_RadioRedditServerIsDownNotification);
        }

        if (!errorGettingStatus && outputStatus.length() > 0) {
            JSONTokener status_tokener = new JSONTokener(outputStatus);
            JSONObject status_json = new JSONObject(status_tokener);

            radiosong.Playlist = status_json.getString("playlist");

            JSONObject songs = status_json.getJSONObject("songs");
            JSONArray songs_array = songs.getJSONArray("song");

            // get the first song in the array
            JSONObject song = songs_array.getJSONObject(0);
            radiosong.ID = song.getInt("id");
            radiosong.Title = song.getString("title");
            radiosong.Artist = song.getString("artist");
            radiosong.Redditor = song.getString("redditor");
            radiosong.Genre = song.getString("genre");
            radiosong.CumulativeScore = song.getString("score");

            if (radiosong.CumulativeScore.equals("{}"))
                radiosong.CumulativeScore = null;

            radiosong.Reddit_title = song.getString("reddit_title");
            radiosong.Reddit_url = song.getString("reddit_url");
            if (song.has("preview_url"))
                radiosong.Preview_url = song.getString("preview_url");
            if (song.has("download_url"))
                radiosong.Download_url = song.getString("download_url");
            if (song.has("bandcamp_link"))
                radiosong.Bandcamp_link = song.getString("bandcamp_link");
            if (song.has("bandcamp_art"))
                radiosong.Bandcamp_art = song.getString("bandcamp_art");
            if (song.has("itunes_link"))
                radiosong.Itunes_link = song.getString("itunes_link");
            if (song.has("itunes_art"))
                radiosong.Itunes_art = song.getString("itunes_art");
            if (song.has("itunes_price"))
                radiosong.Itunes_price = song.getString("itunes_price");

            // get vote score 
            String reddit_info_url = context.getString(R.string.reddit_link_by)
                    + URLEncoder.encode(radiosong.Reddit_url);

            String outputRedditInfo = "";
            boolean errorGettingRedditInfo = false;

            try {
                outputRedditInfo = HTTPUtil.get(context, reddit_info_url);
            } catch (Exception ex) {
                ex.printStackTrace();
                errorGettingRedditInfo = true;
                // For now, not used. It is acceptable to error out and not alert the user
                // radiosong.ErrorMessage = "Unable to connect to reddit";//context.getString(R.string.error_RadioRedditServerIsDownNotification);
            }

            if (!errorGettingRedditInfo && outputRedditInfo.length() > 0) {
                // Log.e("radio_reddit_test", "Length: " + outputRedditInfo.length());
                // Log.e("radio_reddit_test", "Value: " + outputRedditInfo); // TODO: sometimes the value contains "error: 404", need to check for that. (We can probably safely ignore this for now)
                JSONTokener reddit_info_tokener = new JSONTokener(outputRedditInfo);
                JSONObject reddit_info_json = new JSONObject(reddit_info_tokener);

                JSONObject data = reddit_info_json.getJSONObject("data");

                // default value of score
                String score = context.getString(R.string.vote_to_submit_song);
                String likes = "null";
                String name = "";

                JSONArray children_array = data.getJSONArray("children");

                // Song hasn't been submitted yet
                if (children_array.length() > 0) {
                    JSONObject children = children_array.getJSONObject(0);

                    JSONObject children_data = children.getJSONObject("data");
                    score = children_data.getString("score");

                    likes = children_data.getString("likes");
                    name = children_data.getString("name");
                }

                radiosong.Score = score;
                radiosong.Likes = likes;
                radiosong.Name = name;
            } else {
                radiosong.Score = "?";
                radiosong.Likes = "null";
                radiosong.Name = "";
            }

            return radiosong;
        }
        return null;
    } catch (Exception ex) {
        // We fail to get the current song information...
        CustomExceptionHandler ceh = new CustomExceptionHandler(context);
        ceh.sendEmail(ex);

        ex.printStackTrace();
        radiosong.ErrorMessage = ex.toString();
        return radiosong;
    }
}

From source file:net.mandaria.radioreddit.apis.RadioRedditAPI.java

public static RadioEpisode GetCurrentEpisodeInformation(Context context, RadioRedditApplication application) {
    RadioEpisode radioepisode = new RadioEpisode();
    radioepisode.ErrorMessage = "";

    try {/*  w  w  w. j a  v a  2s . c  o m*/
        String status_url = context.getString(R.string.radio_reddit_base_url) + application.CurrentStream.Status
                + context.getString(R.string.radio_reddit_status);

        String outputStatus = "";
        boolean errorGettingStatus = false;

        try {
            outputStatus = HTTPUtil.get(context, status_url);
        } catch (Exception ex) {
            ex.printStackTrace();
            errorGettingStatus = true;
            // For now, not used. It is acceptable to error out and not alert the user
            // radiosong.ErrorMessage = context.getString(R.string.error_RadioRedditServerIsDownNotification);
        }

        if (!errorGettingStatus && outputStatus.length() > 0) {
            JSONTokener status_tokener = new JSONTokener(outputStatus);
            JSONObject status_json = new JSONObject(status_tokener);

            radioepisode.Playlist = status_json.getString("playlist");

            JSONObject episodes = status_json.getJSONObject("episodes");
            JSONArray episodes_array = episodes.getJSONArray("episode");

            // get the first episode in the array
            JSONObject song = episodes_array.getJSONObject(0);
            radioepisode.ID = song.getInt("id");
            radioepisode.EpisodeTitle = song.getString("episode_title");
            radioepisode.EpisodeDescription = song.getString("episode_description");
            radioepisode.EpisodeKeywords = song.getString("episode_keywords");
            radioepisode.ShowTitle = song.getString("show_title");
            radioepisode.ShowHosts = song.getString("show_hosts").replaceAll(",", ", ");
            radioepisode.ShowRedditors = song.getString("show_redditors").replaceAll(",", ", ");
            radioepisode.ShowGenre = song.getString("show_genre");
            radioepisode.ShowFeed = song.getString("show_feed");
            radioepisode.Reddit_title = song.getString("reddit_title");
            radioepisode.Reddit_url = song.getString("reddit_url");
            if (song.has("preview_url"))
                radioepisode.Preview_url = song.getString("preview_url");
            if (song.has("download_url"))
                radioepisode.Download_url = song.getString("download_url");

            // get vote score
            String reddit_info_url = context.getString(R.string.reddit_link_by)
                    + URLEncoder.encode(radioepisode.Reddit_url);

            String outputRedditInfo = "";
            boolean errorGettingRedditInfo = false;

            try {
                outputRedditInfo = HTTPUtil.get(context, reddit_info_url);
            } catch (Exception ex) {
                ex.printStackTrace();
                errorGettingRedditInfo = true;
                // For now, not used. It is acceptable to error out and not alert the user
                // radiosong.ErrorMessage = "Unable to connect to reddit";//context.getString(R.string.error_RadioRedditServerIsDownNotification);
            }

            if (!errorGettingRedditInfo && outputRedditInfo.length() > 0) {
                // Log.e("radio_reddit_test", "Length: " + outputRedditInfo.length());
                // Log.e("radio_reddit_test", "Value: " + outputRedditInfo); // TODO: sometimes the value contains "error: 404", need to check for that (We can probably safely ignore this for now)
                JSONTokener reddit_info_tokener = new JSONTokener(outputRedditInfo);
                JSONObject reddit_info_json = new JSONObject(reddit_info_tokener);

                JSONObject data = reddit_info_json.getJSONObject("data");

                // default value of score
                String score = context.getString(R.string.vote_to_submit_song);
                String likes = "null";
                String name = "";

                JSONArray children_array = data.getJSONArray("children");

                // Episode hasn't been submitted yet
                if (children_array.length() > 0) {
                    JSONObject children = children_array.getJSONObject(0);

                    JSONObject children_data = children.getJSONObject("data");
                    score = children_data.getString("score");

                    likes = children_data.getString("likes");
                    name = children_data.getString("name");
                }

                radioepisode.Score = score;
                radioepisode.Likes = likes;
                radioepisode.Name = name;
            } else {
                radioepisode.Score = "?";
                radioepisode.Likes = "null";
                radioepisode.Name = "";
            }

            return radioepisode;
        }
        return null;
    } catch (Exception ex) {
        // We fail to get the current song information...
        CustomExceptionHandler ceh = new CustomExceptionHandler(context);
        ceh.sendEmail(ex);

        ex.printStackTrace();
        radioepisode.ErrorMessage = ex.toString();
        return radioepisode;
    }

}