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:com.chaosinmotion.securechat.server.commands.ForgotPassword.java

/**
 * Process a forgot password request. This generates a token that the
 * client is expected to return with the change password request.
 * @param requestParams//  w w w  . j  a  v  a  2  s.com
 * @throws SQLException 
 * @throws IOException 
 * @throws ClassNotFoundException 
 * @throws JSONException 
 * @throws NoSuchAlgorithmException 
 */

public static void processRequest(JSONObject requestParams)
        throws SQLException, ClassNotFoundException, IOException, NoSuchAlgorithmException, JSONException {
    String username = requestParams.optString("username");

    /*
     * Step 1: Convert username to the userid for this
     */
    Connection c = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    int userID = 0;
    String retryID = UUID.randomUUID().toString();

    try {
        c = Database.get();
        ps = c.prepareStatement("SELECT userid " + "FROM Users " + "WHERE username = ?");
        ps.setString(1, username);
        rs = ps.executeQuery();
        if (rs.next()) {
            userID = rs.getInt(1);
        }

        if (userID == 0)
            return;
        ps.close();
        rs.close();

        /*
         * Step 2: Generate the retry token and insert into the forgot 
         * database with an expiration date 1 hour from now.
         */

        Timestamp ts = new Timestamp(System.currentTimeMillis() + 3600000);
        ps = c.prepareStatement("INSERT INTO ForgotPassword " + "    ( userid, token, expires ) " + "VALUES "
                + "    ( ?, ?, ?)");
        ps.setInt(1, userID);
        ps.setString(2, retryID);
        ps.setTimestamp(3, ts);
        ps.execute();
    } finally {
        if (rs != null)
            rs.close();
        if (ps != null)
            ps.close();
        if (c != null)
            c.close();
    }

    /*
     * Step 3: formulate a JSON string with the retry and send
     * to the user. The format of the command we send is:
     * 
     * { "cmd": "forgotpassword", "token": token }
     */

    JSONObject obj = new JSONObject();
    obj.put("cmd", "forgotpassword");
    obj.put("token", retryID);
    MessageQueue.getInstance().enqueueAdmin(userID, obj.toString(4));
}

From source file:org.schedulesdirect.grabber.ProgramTask.java

@Override
public void run() {
    long start = System.currentTimeMillis();
    DefaultJsonRequest req = factory.get(DefaultJsonRequest.Action.POST, RestNouns.PROGRAMS, clnt.getHash(),
            clnt.getUserAgent(), clnt.getBaseUrl());
    try {// w  w  w . jav  a2s. co  m
        JSONArray resp = Config.get().getObjectMapper().readValue(req.submitForJson(this.req), JSONArray.class);
        for (int i = 0; i < resp.length(); ++i) {
            JSONObject o = resp.getJSONObject(i);
            String id = o.optString("programID", "<unknown>");
            if (!JsonResponseUtils.isErrorResponse(o)) {
                if (id.startsWith("EP"))
                    seriesIds.add(Program.convertToSeriesId(id));
                Path p = vfs.getPath(targetDir, String.format("%s.txt", id));
                Files.write(p, o.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET), StandardOpenOption.WRITE,
                        StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE);
            } else if (JsonResponseUtils.getErrorCode(o) == ApiResponse.INVALID_PROGID
                    || JsonResponseUtils.getErrorCode(o) == ApiResponse.PROGRAMID_QUEUED) {
                String msg = String.format("Missing program object: %s", id);
                if (!logMissingAtDebug)
                    LOG.warn(msg);
                else
                    LOG.debug(msg);
                if (retrySet != null)
                    retrySet.add(id);
            } else
                throw new InvalidJsonObjectException("Error received for Program", o.toString(3));
        }
    } catch (JSONException | JsonParseException e) {
        Grabber.failedTask = true;
        LOG.error("JSONError!", e);
        throw new RuntimeException(e);
    } catch (IOException e) {
        Grabber.failedTask = true;
        LOG.error("IOError receiving program data; filling in empty program info for non-existent program ids!",
                e);
        try {
            JSONArray ids = this.req;
            for (int i = 0; i < ids.length(); ++i) {
                String id = ids.getString(i);
                Path p = vfs.getPath(targetDir, String.format("%s.txt", id));
                if (!Files.exists(p))
                    Files.write(p, Program.EMPTY_PROGRAM.getBytes(ZipEpgClient.ZIP_CHARSET));
            }
        } catch (Exception x) {
            LOG.error("Unexpected error!", x);
            throw new RuntimeException(x);
        }
    }
    LOG.info(String.format("Completed ProgramTask in %dms [%d programs]", System.currentTimeMillis() - start,
            this.req.length()));
}

From source file:org.zaproxy.zap.extension.exportreport.Export.ReportExport.java

public static File JSON_EXPORT(ViewDelegate view, Logger logger, String absolutePath, String p_result,
        String p_source) {// w w w.  j ava2s  . c  o  m
    int PRETTY_PRINT_INDENT_FACTOR = 4;

    File fXmlFile = new File(p_source);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = null;
    try {
        dBuilder = dbFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        logger.error(e.getMessage(), e);
        view.showWarningDialog(Constant.messages.getString("exportreport.message.error.parser"));
    }
    Document doc = null;
    try {
        doc = dBuilder.parse(fXmlFile);
    } catch (SAXException e) {
        logger.error(e.getMessage(), e);
        view.showWarningDialog(Constant.messages.getString("exportreport.message.error.sax"));
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        view.showWarningDialog(Constant.messages.getString("exportreport.message.error.io"));
    }
    String temp = getStringFromDoc(doc);
    String jsonPrettyPrintString = null;
    try {
        JSONObject xmlJSONObj = XML.toJSONObject(temp);
        jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
    } catch (JSONException e) {
        logger.error(e.getMessage(), e);
        view.showWarningDialog(Constant.messages.getString("exportreport.message.error.json"));
    }
    File f = null;
    try {
        f = write(p_result, jsonPrettyPrintString, false);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        view.showWarningDialog(Constant.messages.getString("exportreport.message.error.exception"));
    }
    return f;
}

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

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

    // Sample usage for each line of NMEA Sentence data
    // GPSPosition a = new GPSPosition();
    // a = parse("$GPGGA,220550,4124.7580,N,08152.2565,W,2,04,4.4,235.1,M,-34.0,M,,*7B");

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

    // Send the stream URL as stream parameter.
    String stream = post.get("stream", "");
    String minified = post.get("minified", "");

    // Download the file/Stream of NMEA data as a buffered stream.
    URL url = new URL(stream);
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
    String NMEALine;

    JSONObject json = new JSONObject(true);
    int lines = 0;

    // Read each buffered stream line by line and parse and convert NMEA to an actual object.
    while ((NMEALine = in.readLine()) != null) {
        lines++;
        GPSPosition gpsObject = new GPSPosition();
        gpsObject = parse(NMEALine);
        json.put(String.valueOf(lines), gpsObject.toJSONString());
    }

    in.close();

    // Start the printwriter and get ready to respond with json
    PrintWriter sos = response.getWriter();
    if (minified != "true") {
        sos.print(json.toString(2));
    } else {
        sos.print(json.toString());
    }
    sos.println();

    post.finalize();
}

From source file:com.cdd.bao.importer.KeywordMapping.java

public void save() throws IOException {
    JSONObject json = new JSONObject();
    JSONArray listID = new JSONArray(), listText = new JSONArray(), listProp = new JSONArray();
    JSONArray listVal = new JSONArray(), listLit = new JSONArray(), listRef = new JSONArray(),
            listAsrt = new JSONArray();

    for (Identifier id : identifiers) {
        JSONObject obj = new JSONObject();
        obj.put("regex", id.regex);
        obj.put("prefix", id.prefix);
        listID.put(obj);/*from  w w  w . ja va2  s . com*/
    }
    for (TextBlock txt : textBlocks) {
        JSONObject obj = new JSONObject();
        obj.put("regex", txt.regex);
        obj.put("title", txt.title);
        listText.put(obj);
    }
    for (Property prop : properties) {
        JSONObject obj = new JSONObject();
        obj.put("regex", prop.regex);
        obj.put("propURI", prop.propURI);
        obj.put("groupNest", prop.groupNest);
        listProp.put(obj);
    }
    for (Value val : values) {
        JSONObject obj = new JSONObject();
        obj.put("regex", val.regex);
        obj.put("valueRegex", val.valueRegex);
        obj.put("valueURI", val.valueURI);
        obj.put("propURI", val.propURI);
        obj.put("groupNest", val.groupNest);
        listVal.put(obj);
    }
    for (Literal lit : literals) {
        JSONObject obj = new JSONObject();
        obj.put("regex", lit.regex);
        obj.put("valueRegex", lit.valueRegex);
        obj.put("propURI", lit.propURI);
        obj.put("groupNest", lit.groupNest);
        listLit.put(obj);
    }
    for (Reference ref : references) {
        JSONObject obj = new JSONObject();
        obj.put("regex", ref.regex);
        obj.put("valueRegex", ref.valueRegex);
        obj.put("prefix", ref.prefix);
        obj.put("propURI", ref.propURI);
        obj.put("groupNest", ref.groupNest);
        listRef.put(obj);
    }
    for (Assertion asrt : assertions) {
        JSONObject obj = new JSONObject();
        obj.put("propURI", asrt.propURI);
        obj.put("groupNest", asrt.groupNest);
        obj.put("valueURI", asrt.valueURI);
        listAsrt.put(obj);
    }

    json.put("identifiers", listID);
    json.put("textBlocks", listText);
    json.put("properties", listProp);
    json.put("values", listVal);
    json.put("literals", listLit);
    json.put("references", listRef);
    json.put("assertions", listAsrt);

    Writer wtr = new FileWriter(file);
    wtr.write(json.toString(2));
    wtr.close();
}

From source file:org.loklak.api.geo.GeocodeServlet.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 w  w. j av  a 2  s  . c om
    }

    // parameters
    String callback = post.get("callback", "");
    boolean jsonp = callback != null && callback.length() > 0;
    boolean minified = post.get("minified", false);
    String data = post.get("data", "");
    String places = post.get("places", "");
    if (places.length() == 0 && data.length() == 0) {
        response.sendError(503,
                "you must submit a data attribut with a json containing the property 'places' with a list of place names");
        return;
    }

    String[] place = new String[0];
    if (places.length() > 0) {
        place = places.split(",");
    } else {
        // parse the json data
        try {
            JSONObject json = new JSONObject(data);
            if (json.has("places") && json.get("places") instanceof JSONArray) {
                JSONArray p = json.getJSONArray("places");
                place = new String[p.length()];
                int i = 0;
                for (Object o : p)
                    place[i++] = (String) o;
            } else {
                response.sendError(400, "submitted data is not well-formed: expected a list of strings");
                return;
            }
        } catch (IOException e) {
            Log.getLog().warn(e);
        }
    }

    // find locations for places
    JSONObject locations = new JSONObject(true);
    for (String p : place) {
        GeoMark loc = DAO.geoNames.analyse(p, null, 5, Long.toString(System.currentTimeMillis()));
        if (loc != null) {
            locations.put(p, loc.toJSON(minified));
        } else {
            locations.put(p, new JSONObject());
        }
    }

    post.setResponse(response, "application/javascript");

    // generate json
    JSONObject m = new JSONObject(true);
    m.put("locations", locations);

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

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

public static JSONObject parseVideo(final BufferedReader br) throws IOException {
    String input;//www . j  a v  a2  s  . c o  m
    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:com.acrutiapps.browser.tasks.HistoryBookmarksExportTask.java

private String writeAsJSON(Cursor... params) {
    try {/*from   w ww .j ava2 s.c  o m*/
        String fileName = mContext.getString(R.string.ApplicationName) + "-" + getNowForFileName() + ".json";

        File file = new File(Environment.getExternalStorageDirectory(), fileName);
        FileWriter writer = new FileWriter(file);

        FoldersJSONArray foldersArray = new FoldersJSONArray();
        BookmarksJSONArray bookmarksArray = new BookmarksJSONArray();
        HistoryJSONArray historyArray = new HistoryJSONArray();

        Cursor c = params[0];
        if (c.moveToFirst()) {

            int current = 0;
            int total = c.getCount();

            int idIndex = c.getColumnIndex(BookmarksProvider.Columns._ID);
            int titleIndex = c.getColumnIndex(BookmarksProvider.Columns.TITLE);
            int urlIndex = c.getColumnIndex(BookmarksProvider.Columns.URL);
            int creationDateIndex = c.getColumnIndex(BookmarksProvider.Columns.CREATION_DATE);
            int visitedDateIndex = c.getColumnIndex(BookmarksProvider.Columns.VISITED_DATE);
            int visitsIndex = c.getColumnIndex(BookmarksProvider.Columns.VISITS);
            int bookmarkIndex = c.getColumnIndex(BookmarksProvider.Columns.BOOKMARK);
            int folderIndex = c.getColumnIndex(BookmarksProvider.Columns.IS_FOLDER);
            int parentfolderIdIndex = c.getColumnIndex(BookmarksProvider.Columns.PARENT_FOLDER_ID);

            while (!c.isAfterLast()) {

                publishProgress(1, current, total);

                boolean isFolder = c.getInt(folderIndex) > 0 ? true : false;

                if (isFolder) {
                    String title = c.getString(titleIndex);
                    title = title != null ? URLEncoder.encode(title, "UTF-8") : "";

                    foldersArray.add(title, c.getLong(idIndex), c.getLong(parentfolderIdIndex));

                } else {
                    boolean isBookmark = c.getInt(bookmarkIndex) > 0 ? true : false;

                    String title = c.getString(titleIndex);
                    title = title != null ? URLEncoder.encode(title, "UTF-8") : "";

                    String url = c.getString(urlIndex);
                    url = url != null ? URLEncoder.encode(url, "UTF-8") : "";

                    if (isBookmark) {
                        bookmarksArray.add(c.getLong(parentfolderIdIndex), title, url,
                                c.getLong(creationDateIndex), c.getLong(visitedDateIndex),
                                c.getInt(visitsIndex));
                    } else {
                        historyArray.add(title, url, c.getLong(visitedDateIndex), c.getInt(visitsIndex));
                    }
                }

                current++;
                c.moveToNext();
            }
        }

        JSONObject output = new JSONObject();
        output.put("folders", foldersArray);
        output.put("bookmarks", bookmarksArray);
        output.put("history", historyArray);

        writer.write(output.toString(1));

        writer.flush();
        writer.close();

    } catch (JSONException e) {
        e.printStackTrace();
        return e.getMessage();
    } catch (IOException e) {
        e.printStackTrace();
        return e.getMessage();
    }

    return null;
}

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

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

    String eqBaseUrl = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/";

    // Earthquakes happening per hour.
    String SIGNIFICANT_HOUR = "summary/significant_hour.geojson";
    String MAGNITUDE_4_5_HOUR = "summary/4.5_hour.geojson";
    String MAGNITUDE_2_5_HOUR = "summary/2.5_hour.geojson";
    String MAGNITUDE_1_0_HOUR = "summary/1.0_hour.geojson";
    String ALL_HOUR = "summary/all_hour.geojson";

    // Earthquakes happening per day.
    String SIGNIFICANT_DAY = "summary/significant_day.geojson";
    String MAGNITUDE_4_5_DAY = "summary/4.5_day.geojson";
    String MAGNITUDE_2_5_DAY = "summary/2.5_day.geojson";
    String MAGNITUDE_1_0_DAY = "summary/1.0_day.geojson";
    String ALL_DAY = "summary/all_day.geojson";

    // Earthquakes in the last 7 days.
    String SIGNIFICANT_WEEK = "summary/significant_week.geojson";
    String MAGNITUDE_4_5_WEEK = "summary/4.5_week.geojson";
    String MAGNITUDE_2_5_WEEK = "summary/2.5_week.geojson";
    String MAGNITUDE_1_0_WEEK = "summary/1.0_week.geojson";
    String ALL_WEEK = "summary/all_week.geojson";

    // Earthquakes in the last 30 days.
    String SIGNIFICANT_MONTH = "summary/significant_month.geojson";
    String MAGNITUDE_4_5_MONTH = "summary/4.5_month.geojson";
    String MAGNITUDE_2_5_MONTH = "summary/2.5_month.geojson";
    String MAGNITUDE_1_0_MONTH = "summary/1.0_month.geojson";
    String ALL_MONTH = "summary/all_month.geojson";

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

    String duration = post.get("duration", "");
    String magnitude = post.get("magnitude", "");

    String earthquakeQueryURL = "";

    if ("hour".equals(duration)) {
        if ("4.5".equals(magnitude)) {
            earthquakeQueryURL = eqBaseUrl + MAGNITUDE_4_5_HOUR;
        } else if ("2.5".equals(magnitude)) {
            earthquakeQueryURL = eqBaseUrl + MAGNITUDE_2_5_HOUR;
        } else if ("1.0".equals(magnitude)) {
            earthquakeQueryURL = eqBaseUrl + MAGNITUDE_1_0_HOUR;
        } else if ("significant".equals(magnitude)) {
            earthquakeQueryURL = eqBaseUrl + SIGNIFICANT_HOUR;
        } else {
            earthquakeQueryURL = eqBaseUrl + ALL_HOUR;
        }
    } else if ("day".equals(duration)) {
        if ("4.5".equals(magnitude)) {
            earthquakeQueryURL = eqBaseUrl + MAGNITUDE_4_5_DAY;
        } else if ("2.5".equals(magnitude)) {
            earthquakeQueryURL = eqBaseUrl + MAGNITUDE_2_5_DAY;
        } else if ("1.0".equals(magnitude)) {
            earthquakeQueryURL = eqBaseUrl + MAGNITUDE_1_0_DAY;
        } else if ("significant".equals(magnitude)) {
            earthquakeQueryURL = eqBaseUrl + SIGNIFICANT_DAY;
        } else {
            earthquakeQueryURL = eqBaseUrl + ALL_DAY;
        }
    } else if ("week".equals(duration)) {
        if ("4.5".equals(magnitude)) {
            earthquakeQueryURL = eqBaseUrl + MAGNITUDE_4_5_WEEK;
        } else if ("2.5".equals(magnitude)) {
            earthquakeQueryURL = eqBaseUrl + MAGNITUDE_2_5_WEEK;
        } else if ("1.0".equals(magnitude)) {
            earthquakeQueryURL = eqBaseUrl + MAGNITUDE_1_0_WEEK;
        } else if ("significant".equals(magnitude)) {
            earthquakeQueryURL = eqBaseUrl + SIGNIFICANT_WEEK;
        } else {
            earthquakeQueryURL = eqBaseUrl + ALL_WEEK;
        }
    } else if ("month".equals(duration)) {
        if ("4.5".equals(magnitude)) {
            earthquakeQueryURL = eqBaseUrl + MAGNITUDE_4_5_MONTH;
        } else if ("2.5".equals(magnitude)) {
            earthquakeQueryURL = eqBaseUrl + MAGNITUDE_2_5_MONTH;
        } else if ("1.0".equals(magnitude)) {
            earthquakeQueryURL = eqBaseUrl + MAGNITUDE_1_0_MONTH;
        } else if ("significant".equals(magnitude)) {
            earthquakeQueryURL = eqBaseUrl + SIGNIFICANT_MONTH;
        } else {
            earthquakeQueryURL = eqBaseUrl + ALL_MONTH;
        }
    } else {
        earthquakeQueryURL = eqBaseUrl + SIGNIFICANT_HOUR;
    }
    // earthquakeQueryURL = eqBaseUrl + MAGNITUDE_1_0_MONTH;

    JSONObject json = readJsonFromUrl(earthquakeQueryURL);
    json.put("query", earthquakeQueryURL);

    PrintWriter sos = response.getWriter();
    sos.print(json.toString(2));
    sos.println();
}

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

/**
 * Get parameters//from w ww .jav a  2  s .c  o m
 *
 * @param hit String
 * @return HashMap
 */
static LinkedHashMap<String, String> getParameters(String hit) {
    LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
    try {
        URL url = new URL(hit);
        map.put("ssl", url.getProtocol().equals("http") ? "Off" : "On");
        map.put("log", url.getHost());
        String[] queryComponents = url.getQuery().split("&");
        for (String queryComponent : queryComponents) {
            String[] elem = queryComponent.split("=");
            if (elem.length > 1) {
                elem[1] = Tool.percentDecode(elem[1]);
                if (Tool.parseJSON(elem[1]) instanceof JSONObject) {
                    JSONObject json = (JSONObject) Tool.parseJSON(elem[1]);
                    if (json != null && elem[0].equals(Hit.HitParam.JSON.stringValue())) {
                        map.put(elem[0], json.toString(3));
                    } else {
                        map.put(elem[0], elem[1]);
                    }
                } else {
                    map.put(elem[0], elem[1]);
                }
            } else {
                map.put(elem[0], "");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return map;
}