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

Source Link

Document

Construct an empty JSONObject.

Usage

From source file:cn.xdf.thinkutils.http2.JsonHttpResponseHandler.java

@Override
protected void sendSuccessMessage(int statusCode, Header[] headers, String responseBody) {
    if (statusCode != HttpStatus.SC_NO_CONTENT) {
        try {//ww w.j a va 2s  .c  o m
            Object jsonResponse = parseResponse(responseBody);
            sendMessage(
                    obtainMessage(SUCCESS_JSON_MESSAGE, new Object[] { statusCode, headers, jsonResponse }));
        } catch (JSONException e) {
            sendFailureMessage(e, responseBody);
        }
    } else {
        sendMessage(obtainMessage(SUCCESS_JSON_MESSAGE, new Object[] { statusCode, new JSONObject() }));
    }
}

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

/**
 *  JSON //ww  w . j a va  2  s .c o  m
 * @param queue
 * @return
 */
private JSONArray convert(ArrayList<String> identifiers, ArrayList<Primitive> list) {
    JSONArray ret = new JSONArray();

    try {
        for (int i = 0, size = identifiers.size(); i < size; ++i) {
            String identifier = identifiers.get(i);
            Primitive prim = list.get(i);

            JSONObject primJson = new JSONObject();
            PrimitiveSerializer.write(primJson, prim);

            JSONObject json = new JSONObject();
            json.put(Identifier, identifier);
            json.put(Primitive, primJson);

            // 
            ret.put(json);
        }
    } catch (JSONException e) {
        // Nothing
    }

    return ret;
}

From source file:kr.ac.cau.mecs.cass.servletcontextlistener.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    onServletInit(request, response);/* www.j  a v a  2 s.co m*/

    response.setContentType("application/json; charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");

    PrintWriter out = response.getWriter();
    JSONObject jobj = new JSONObject();

    Transaction tx = null;
    Session hsession = HibernateSessionFactory.getSessionFactory().getCurrentSession();

    try {
        tx = hsession.beginTransaction();

        jobj = processGet(hsession, request, response);

        tx.commit();
    } catch (Exception e) {
        jobj.putOpt("error", 1);
        jobj.putOpt("reason", "server transaction error");
        jobj.putOpt("msg", e.getMessage());
        e.printStackTrace();
        if (tx != null && tx.isActive()) {
            try {
                tx.rollback();
            } catch (HibernateException e1) {
                e1.printStackTrace();
            }
        }
    }

    jobj.write(out);
    out.close();

}

From source file:kr.ac.cau.mecs.cass.servletcontextlistener.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    onServletInit(request, response);//from  w  w w  .  j  a va 2s.c o  m

    response.setContentType("application/json; charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");

    PrintWriter out = response.getWriter();
    JSONObject jobj = new JSONObject();

    Transaction tx = null;
    Session hsession = HibernateSessionFactory.getSessionFactory().getCurrentSession();

    try {
        tx = hsession.beginTransaction();

        jobj = processPost(hsession, request, response);

        tx.commit();
    } catch (Exception e) {
        jobj.putOpt("error", 1);
        jobj.putOpt("reason", "server transaction error");
        jobj.putOpt("msg", e.getMessage());

        e.printStackTrace();
        if (tx != null && tx.isActive()) {
            try {
                tx.rollback();
            } catch (HibernateException e1) {
                e1.printStackTrace();
            }
        }
    }

    jobj.write(out);
    out.close();
}

From source file:org.jahia.modules.modulemanager.flow.DuplicateModuleAction.java

@Override
public ActionResult doExecute(HttpServletRequest req, RenderContext renderContext, Resource resource,
        JCRSessionWrapper session, Map<String, List<String>> parameters, URLResolver urlResolver)
        throws Exception {

    String newModuleName = getParameter(parameters, "newModuleName");
    String newModuleId = getParameter(parameters, "newModuleId");
    String newGroupId = getParameter(parameters, "newGroupId");
    String newDstPath = getParameter(parameters, "newDstPath");

    String srcPath = getParameter(parameters, "srcPath");
    String newScmUri = getParameter(parameters, "newScmUri");
    String branchOrTag = getParameter(parameters, "branchOrTag");
    String moduleId = getParameter(parameters, "moduleId");
    String version = getParameter(parameters, "version");
    boolean containsTypeDefinitions = Boolean
            .valueOf(getParameter(parameters, "containsTypeDefinitions", "false"));
    boolean areSourcesTemporary = Boolean.valueOf(getParameter(parameters, "areSourcesTemporary", "false"));

    try {/*from  ww  w.ja  v a 2 s  . c o m*/
        JahiaTemplatesPackage newModule = jahiaTemplateManagerService.duplicateModule(newModuleName,
                newModuleId, newGroupId, srcPath, newScmUri, branchOrTag, moduleId, version,
                containsTypeDefinitions, newDstPath, areSourcesTemporary, session);
        String contextPath = renderContext.getRequest().getContextPath();
        String newModuleStudioUrl = (StringUtils.equals(contextPath, "/") ? "" : contextPath)
                + "/cms/studio/default/" + resource.getLocale() + "/modules/" + newModule.getId() + ".html";
        JSONObject json = new JSONObject();
        json.put("newModuleStudioUrl", newModuleStudioUrl);
        return new ActionResult(HttpServletResponse.SC_OK, null, json);
    } catch (ScmUnavailableModuleIdException e) {
        String message = Messages.getWithArgs("resources.ModuleManager",
                "serverSettings.manageModules.duplicateModuleError.moduleExists", resource.getLocale(),
                newModuleName);
        JSONObject json = new JSONObject();
        json.put("error", message);
        return new ActionResult(HttpServletResponse.SC_OK, null, json);
    } catch (ScmWrongVersionException e) {
        String message = Messages.get("resources.ModuleManager",
                "serverSettings.manageModules.downloadSourcesError.wrongVersion", resource.getLocale());
        JSONObject json = new JSONObject();
        json.put("error", message);
        return new ActionResult(HttpServletResponse.SC_OK, null, json);
    } catch (SourceControlException e) {
        String message = Messages.getWithArgs("resources.ModuleManager",
                "serverSettings.manageModules.downloadSourcesError", resource.getLocale(), version);
        JSONObject json = new JSONObject();
        json.put("error", message);
        return new ActionResult(HttpServletResponse.SC_OK, null, json);
    } catch (Exception e) {
        String message = e.getLocalizedMessage();
        if (StringUtils.isBlank(message)) {
            message = e.toString();
        }
        JSONObject json = new JSONObject();
        json.put(e instanceof BundleException ? "bundleError" : "error", message);
        return new ActionResult(HttpServletResponse.SC_OK, null, json);
    }
}

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

public void saveResult() {
    if (result == null)
        return;/*w  ww  .  j a  v a 2s.c o  m*/

    JSONObject jsonResult = new JSONObject();

    JSONArray jsonCards = new JSONArray();
    for (Card card : result.getCards()) {
        jsonCards.put(card.getName());
    }

    try {
        jsonResult.put("cards", jsonCards);
        if (result.getBaneCard() != null) {
            jsonResult.put("baneCard", result.getBaneCard().getName());
        }
        if (result.getObeliskCard() != null) {
            jsonResult.put("obeliskCard", result.getObeliskCard().getName());
        }
        DataReader.writeStringToFile(this, "result.json", jsonResult.toString());
    } catch (JSONException ignore) {
        ignore.printStackTrace();
    }
}

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//from  w  w w .  j  av  a  2 s  .co m
 * @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:example.SendNumbers.java

/**
 * @param args//from   ww w  .  j a  v  a 2  s  .c  o  m
 * @throws MalformedURLException
 */
public static void main(String[] args) throws MalformedURLException {

    AEONSDK sdk = new AEONSDK(Config.PUB_URL);

    for (int i = 0; i <= 500; i++) {
        JSONObject data = new JSONObject();
        try {
            data.put("number", i);
            System.out.println(data.toString());
            sdk.publish(data, new MyAEONCallbacks());
            TimeUnit.MICROSECONDS.sleep(200);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

From source file:github.popeen.dsub.util.SongDBHandler.java

public JSONArray exportData() {
    SQLiteDatabase db = this.getReadableDatabase();
    String[] columns = { SONGS_ID, SONGS_SERVER_KEY, SONGS_SERVER_ID, SONGS_COMPLETE_PATH, SONGS_LAST_PLAYED,
            SONGS_LAST_COMPLETED };//from w w  w.ja  v  a  2s . co  m
    Cursor cursor = db.query(TABLE_SONGS, columns, SONGS_LAST_PLAYED + " != ''", null, null, null, null, null);
    try {
        JSONArray jsonSongDb = new JSONArray();
        while (cursor.moveToNext()) {
            JSONObject tempJson = new JSONObject();
            tempJson.put("SONGS_ID", cursor.getInt(0));
            tempJson.put("SONGS_SERVER_KEY", cursor.getInt(1));
            tempJson.put("SONGS_SERVER_ID", cursor.getString(2));
            tempJson.put("SONGS_COMPLETE_PATH", cursor.getString(3));
            tempJson.put("SONGS_LAST_PLAYED", cursor.getInt(4));
            tempJson.put("SONGS_LAST_COMPLETED", cursor.getInt(5));
            jsonSongDb.put(tempJson);
        }
        cursor.close();
        return jsonSongDb;
    } catch (Exception e) {
    }
    return new JSONArray();
}

From source file:com.stockbrowser.view.BookmarkExpandableView.java

public JSONObject saveGroupState() throws JSONException {
    JSONObject obj = new JSONObject();
    int count = mAdapter.getGroupCount();
    for (int i = 0; i < count; i++) {
        String acctName = mAdapter.mGroups.get(i);
        if (!isGroupExpanded(i)) {
            obj.put(acctName != null ? acctName : LOCAL_ACCOUNT_NAME, false);
        }/*w w w  .  j a v a 2s  .com*/
    }
    return obj;
}