Example usage for org.json JSONObject keys

List of usage examples for org.json JSONObject keys

Introduction

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

Prototype

public Iterator keys() 

Source Link

Document

Get an enumeration of the keys of the JSONObject.

Usage

From source file:com.phonegap.FileTransfer.java

/**
 * Uploads the specified file to the server URL provided using an HTTP 
 * multipart request. /*from  w ww  . j av  a  2s  .  c  o m*/
 * @param file      Full path of the file on the file system
 * @param server        URL of the server to receive the file
 * @param fileKey       Name of file request parameter
 * @param fileName      File name to be used on server
 * @param mimeType      Describes file content type
 * @param params        key:value pairs of user-defined parameters
 * @return FileUploadResult containing result of upload request
 */
public FileUploadResult upload(String file, String server, final String fileKey, final String fileName,
        final String mimeType, JSONObject params, boolean trustEveryone) throws IOException, SSLException {
    // Create return object
    FileUploadResult result = new FileUploadResult();

    // Get a input stream of the file on the phone
    InputStream fileInputStream = getPathFromUri(file);

    HttpURLConnection conn = null;
    DataOutputStream dos = null;

    int bytesRead, bytesAvailable, bufferSize;
    long totalBytes;
    byte[] buffer;
    int maxBufferSize = 8096;

    //------------------ CLIENT REQUEST
    // open a URL connection to the server 
    URL url = new URL(server);

    // Open a HTTP connection to the URL based on protocol 
    if (url.getProtocol().toLowerCase().equals("https")) {
        // Using standard HTTPS connection. Will not allow self signed certificate
        if (!trustEveryone) {
            conn = (HttpsURLConnection) url.openConnection();
        }
        // Use our HTTPS connection that blindly trusts everyone.
        // This should only be used in debug environments
        else {
            // Setup the HTTPS connection class to trust everyone
            trustAllHosts();
            HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
            // Save the current hostnameVerifier
            defaultHostnameVerifier = https.getHostnameVerifier();
            // Setup the connection not to verify hostnames 
            https.setHostnameVerifier(DO_NOT_VERIFY);
            conn = https;
        }
    }
    // Return a standard HTTP conneciton
    else {
        conn = (HttpURLConnection) url.openConnection();
    }

    // Allow Inputs
    conn.setDoInput(true);

    // Allow Outputs
    conn.setDoOutput(true);

    // Don't use a cached copy.
    conn.setUseCaches(false);

    // Use a post method.
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDRY);

    // Set the cookies on the response
    String cookie = CookieManager.getInstance().getCookie(server);
    if (cookie != null) {
        conn.setRequestProperty("Cookie", cookie);
    }

    dos = new DataOutputStream(conn.getOutputStream());

    // Send any extra parameters
    try {
        for (Iterator iter = params.keys(); iter.hasNext();) {
            Object key = iter.next();
            dos.writeBytes(LINE_START + BOUNDRY + LINE_END);
            dos.writeBytes("Content-Disposition: form-data; name=\"" + key.toString() + "\"; ");
            dos.writeBytes(LINE_END + LINE_END);
            dos.writeBytes(params.getString(key.toString()));
            dos.writeBytes(LINE_END);
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }

    dos.writeBytes(LINE_START + BOUNDRY + LINE_END);
    dos.writeBytes("Content-Disposition: form-data; name=\"" + fileKey + "\";" + " filename=\"" + fileName
            + "\"" + LINE_END);
    dos.writeBytes("Content-Type: " + mimeType + LINE_END);
    dos.writeBytes(LINE_END);

    // create a buffer of maximum size
    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];

    // read file and write it into form...
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    totalBytes = 0;

    while (bytesRead > 0) {
        totalBytes += bytesRead;
        result.setBytesSent(totalBytes);
        dos.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }

    // send multipart form data necesssary after file data...
    dos.writeBytes(LINE_END);
    dos.writeBytes(LINE_START + BOUNDRY + LINE_START + LINE_END);

    // close streams
    fileInputStream.close();
    dos.flush();
    dos.close();

    //------------------ read the SERVER RESPONSE
    StringBuffer responseString = new StringBuffer("");
    DataInputStream inStream = new DataInputStream(conn.getInputStream());
    String line;
    while ((line = inStream.readLine()) != null) {
        responseString.append(line);
    }
    Log.d(LOG_TAG, "got response from server");
    Log.d(LOG_TAG, responseString.toString());

    // send request and retrieve response
    result.setResponseCode(conn.getResponseCode());
    result.setResponse(responseString.toString());

    inStream.close();
    conn.disconnect();

    // Revert back to the proper verifier and socket factories
    if (trustEveryone && url.getProtocol().toLowerCase().equals("https")) {
        ((HttpsURLConnection) conn).setHostnameVerifier(defaultHostnameVerifier);
        HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
    }

    return result;
}

From source file:com.soomla.store.domain.virtualGoods.SingleUsePackVG.java

/**
 * see parent//w  w w  .  jav a  2  s.  c  o m
 */
@Override
public JSONObject toJSONObject() {
    JSONObject parentJsonObject = super.toJSONObject();
    JSONObject jsonObject = new JSONObject();
    try {
        Iterator<?> keys = parentJsonObject.keys();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            jsonObject.put(key, parentJsonObject.get(key));
        }

        jsonObject.put(JSONConsts.VGP_GOOD_ITEMID, mGoodItemId);
        jsonObject.put(JSONConsts.VGP_GOOD_AMOUNT, mGoodAmount);
    } catch (JSONException e) {
        StoreUtils.LogError(TAG, "An error occurred while generating JSON object.");
    }

    return jsonObject;
}

From source file:com.ubikod.capptain.android.sdk.track.CapptainTrackReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    /* Once the application identifier is known */
    if ("com.ubikod.capptain.intent.action.APPID_GOT".equals(intent.getAction())) {
        /* Init the tracking agent */
        String appId = intent.getStringExtra("appId");
        CapptainTrackAgent.getInstance(context).onAppIdGot(appId);
    }//from   w w w  .j  a  va 2  s .  co  m

    /* During installation, an install referrer may be triggered */
    else if ("com.android.vending.INSTALL_REFERRER".equals(intent.getAction())) {
        /* Forward this action to configured receivers */
        String forwardList = CapptainUtils.getMetaData(context)
                .getString("capptain:track:installReferrerForwardList");
        if (forwardList != null)
            for (String component : forwardList.split(","))
                if (!component.equals(getClass().getName())) {
                    Intent clonedIntent = new Intent(intent);
                    clonedIntent.setComponent(new ComponentName(context, component));
                    context.sendBroadcast(clonedIntent);
                }

        /* Guess store from referrer */
        String referrer = Uri.decode(intent.getStringExtra("referrer"));
        String store;

        /* GetJar uses an opaque string always starting with z= */
        if (referrer.startsWith("z="))
            store = "GetJar";

        /* Assume Android Market otherwise */
        else
            store = "Android Market";

        /* Look for a source parameter */
        Uri uri = Uri.parse("a://a?" + referrer);
        String source = uri.getQueryParameter("utm_source");

        /*
         * Skip "androidmarket" source, this is the default one when not set or installed via web
         * Android Market.
         */
        if ("androidmarket".equals(source))
            source = null;

        /* Send app info to register store/source */
        Bundle appInfo = new Bundle();
        appInfo.putString("store", store);
        if (source != null) {
            /* Parse source, if coming from capptain, it may be a JSON complex object */
            try {
                /* Convert JSON to bundle (just flat strings) */
                JSONObject jsonInfo = new JSONObject(source);
                Iterator<?> keyIt = jsonInfo.keys();
                while (keyIt.hasNext()) {
                    String key = keyIt.next().toString();
                    appInfo.putString(key, jsonInfo.getString(key));
                }
            } catch (JSONException jsone) {
                /* Not an object, process as a string */
                appInfo.putString("source", source);
            }
        }

        /* Send app info */
        CapptainAgent.getInstance(context).sendAppInfo(appInfo);
    }
}

From source file:m.dekmak.Database.java

public String editUser(String oldUsername, String newUsername, JSONObject newRoles) {
    String msg = "";
    try {//from   w  w  w  .j  a v  a  2s .c o  m
        int completeScript = 1;
        int updateUsername = 0;
        statement = connection.createStatement();

        // check if username has changed and the new value is already taken and exists in db. else, update username in db  
        if (!oldUsername.equals(newUsername)) {
            preparedStatement = connection.prepareStatement("select user_name from users where user_name = ?");
            preparedStatement.setString(1, newUsername);
            ResultSet rs = preparedStatement.executeQuery();
            String dbUserName = "";
            while (rs.next()) {
                dbUserName = rs.getString("user_name");
            }
            if (dbUserName != "") { // new username already exists in DB
                msg = "The new username already taken. Please choose another";
                completeScript = 0;
            } else {
                updateUsername = 1;
            }
        }
        if (completeScript == 1) {
            // remove old roles
            statement = connection.createStatement();
            preparedStatement = connection
                    .prepareStatement("delete from users_roles where users_roles.user_name = ?");
            preparedStatement.setString(1, oldUsername);
            if (preparedStatement.executeUpdate() == 0) {
                msg = "Failed to change roles (db problem)";
                completeScript = 0;
            } else {
                msg = "success";
                completeScript = 1;
            }
            if (completeScript == 1) {
                if (updateUsername == 1) {
                    // update username in DB
                    statement = connection.createStatement();
                    preparedStatement = connection
                            .prepareStatement("update users set users.user_name = ? where users.user_name = ?");
                    preparedStatement.setString(1, newUsername);
                    preparedStatement.setString(2, oldUsername);
                    if (preparedStatement.executeUpdate() == 0) {
                        msg = "Failed to change username (db problem)";
                        completeScript = 0;
                    } else {
                        msg = "success";
                        completeScript = 1;
                    }
                }
                if (completeScript == 1) {
                    // insert new roles
                    Iterator<?> roles = newRoles.keys();
                    while (roles.hasNext()) {
                        String role = (String) roles.next();
                        statement = connection.createStatement();
                        preparedStatement = connection.prepareStatement(
                                "INSERT INTO users_roles" + "(user_name, role_name) VALUES" + "(?,?)");
                        preparedStatement.setString(1, newUsername);
                        preparedStatement.setString(2, role);
                        preparedStatement.executeUpdate();
                    }
                }
            }
        }
    } catch (Exception e) {
        msg = "Exception message: " + e.getMessage();
    }
    return msg;
}

From source file:m.dekmak.Database.java

public String addUser(String user_name, JSONObject user_groups, String password) {
    String msg = "";
    int completeScript = 1;
    try {//from  w w w  .ja v a 2 s . c  o m
        MD5Digest md5 = new MD5Digest();
        String hashPwd = md5.generate(password);
        Encryptor encr = new Encryptor(hashPwd);
        String pass2 = encr.encrypt(password);
        statement = connection.createStatement();
        preparedStatement = connection.prepareStatement("select user_name from users where user_name = ?");
        preparedStatement.setString(1, user_name);
        ResultSet rs = preparedStatement.executeQuery();
        String dbUserName = "";
        while (rs.next()) {
            dbUserName = rs.getString("user_name");
        }
        if (dbUserName != "") { // username already exists in DB
            msg = "Username already taken. Please choose another";
            completeScript = 0;
        } else {
            preparedStatement = connection
                    .prepareStatement("INSERT INTO users" + "(user_name, password, pass2) VALUES" + "(?,?,?)");
            preparedStatement.setString(1, user_name);
            preparedStatement.setString(2, hashPwd);
            preparedStatement.setString(3, pass2);
            if (preparedStatement.executeUpdate() == 0) {
                msg = "Failed to add user (db problem)";
            } else {
                msg = "success";
                // link roles
                Iterator<?> roles = user_groups.keys();
                while (roles.hasNext()) {
                    String role = (String) roles.next();
                    statement = connection.createStatement();
                    preparedStatement = connection.prepareStatement(
                            "INSERT INTO users_roles" + "(user_name, role_name) VALUES" + "(?,?)");
                    preparedStatement.setString(1, user_name);
                    preparedStatement.setString(2, role);
                    preparedStatement.executeUpdate();
                }
            }
        }
    } catch (Exception e) {
        msg = "Exception message: " + e.getMessage();
    }
    return msg;
}

From source file:m.dekmak.Database.java

public String notifyUser(String message, JSONObject users_list, String sendByEmail) {
    String msg = "";
    try {/* w  w  w  .j av  a2  s .c o m*/
        msg = "success";
        Iterator<?> users = users_list.keys();
        while (users.hasNext()) {
            String user = (String) users.next();
            statement = connection.createStatement();
            preparedStatement = connection.prepareStatement("INSERT INTO notifications"
                    + "(message, user_name, status, sentDate) VALUES" + "(?,?,?,?)");
            message = message.replaceAll(",", "&comma&");
            preparedStatement.setString(1, message);
            preparedStatement.setString(2, user);
            preparedStatement.setString(3, "unseen");
            preparedStatement.setDate(4, getCurrentDate());
            preparedStatement.executeUpdate();
            if (sendByEmail.equals("yes")) {
                statement = connection.createStatement();
                preparedStatement = connection.prepareStatement("select email from users where user_name = ?");
                preparedStatement.setString(1, user);
                ResultSet rs = preparedStatement.executeQuery();
                while (rs.next()) {
                    String userEmail = rs.getString("email");
                    if (userEmail != null && !userEmail.isEmpty()) {
                        Email email = new Email();
                        message = message.replaceAll("&comma&", ",");
                        msg = email.send(userEmail, message);
                        if (msg.equals("Done")) {
                            msg = "success";
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        msg = "Exception message: " + e.getMessage();
    }
    return msg;
}

From source file:m.dekmak.Database.java

public int addEvent(String title, String start, String end, String location, JSONObject users,
        String createdBy) {//from   ww  w. j  av a 2 s. c om
    int id = 0;
    try {
        statement = connection.createStatement();
        preparedStatement = connection.prepareStatement(
                "INSERT INTO calendar" + "(title, start, end, location, createdBy) VALUES" + "(?,?,?,?,?)");
        preparedStatement.setString(1, title.replaceAll(",", "&comma&"));
        preparedStatement.setString(2, start);
        preparedStatement.setString(3, end);
        preparedStatement.setString(4, location.replaceAll(",", "&comma&"));
        preparedStatement.setString(5, createdBy);
        int affectedRows = preparedStatement.executeUpdate();
        if (affectedRows != 0) {
            ResultSet generatedKeys = preparedStatement.getGeneratedKeys();
            if (generatedKeys.next()) {
                id = (int) generatedKeys.getLong(1);
                Iterator<?> invities = users.keys();
                while (invities.hasNext()) {
                    String user = (String) invities.next();
                    statement = connection.createStatement();
                    preparedStatement = connection.prepareStatement(
                            "INSERT INTO calendar_users" + "(event_id, user_name) VALUES" + "(?,?)");
                    preparedStatement.setInt(1, id);
                    preparedStatement.setString(2, user);
                    if (preparedStatement.executeUpdate() != 0) {
                        statement = connection.createStatement();
                        preparedStatement = connection
                                .prepareStatement("select email from users where user_name = ?");
                        preparedStatement.setString(1, user);
                        ResultSet rs = preparedStatement.executeQuery();
                        while (rs.next()) {
                            String userEmail = rs.getString("email");
                            if (userEmail != null && !userEmail.isEmpty()) {
                                Email email = new Email();
                                String message = "Hi " + user + ",\n\n"
                                        + "You have invited to the below event: \n\n" + "Title: "
                                        + title.replaceAll("&comma&", ",") + "\n" + "Start date: " + start
                                        + "\n" + "End date: " + end + "\n" + "Location: " + location;
                                String msg = email.send(userEmail, message);
                            }
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
    }
    return id;
}

From source file:m.dekmak.Database.java

public JSONObject readEvents(JSONObject users) {
    JSONObject jsO = new JSONObject();
    try {// w  w w . j av a2 s  . c  o  m
        StringBuilder inClause = new StringBuilder();
        Iterator<?> invities = users.keys();
        while (invities.hasNext()) {
            String user = (String) invities.next();
            inClause.append('?');
            inClause.append(',');
        }
        if (inClause.length() > 0) {
            inClause.setLength(inClause.length() - 1);
        }
        statement = connection.createStatement();
        preparedStatement = connection.prepareStatement(
                "select * from calendar left join calendar_users on calendar_users.event_id = calendar.id where id >= ? AND calendar_users.user_name in ("
                        + inClause.toString() + ") group by calendar_users.event_id");
        preparedStatement.setInt(1, 1);
        Iterator<?> invitiesList = users.keys();
        int i = 2;
        while (invitiesList.hasNext()) {
            String user = (String) invitiesList.next();
            preparedStatement.setString(i, user);
            i++;
        }
        ResultSet rs = preparedStatement.executeQuery();
        while (rs.next()) {
            JSONObject jsO2 = new JSONObject();
            jsO2.put("id", rs.getString("id"));
            jsO2.put("title", rs.getString("title"));
            jsO2.put("start", rs.getString("start"));
            jsO2.put("end", rs.getString("end"));
            jsO2.put("location", rs.getString("location"));
            jsO.put(rs.getString("id"), jsO2);
        }
    } catch (Exception e) {
    }
    return jsO;
}

From source file:edu.txstate.dmlab.clusteringwiki.rest.TestController.java

/**
 * Save the details of the last executed step
 * @param executionId the execution id for the current test
 * @param model//from  w w w  .  ja  va 2 s  . co m
 * @return
 * @throws Exception
 */
@SuppressWarnings("unchecked")
@RequestMapping("/test/put/{executionId}")
public void saveStep(@PathVariable("executionId") String execId, HttpServletRequest request,
        HttpServletResponse response, Model model) throws Exception {

    String executionId = _cleanExtensions(execId);

    if (!isValidTest(request, executionId)) {
        sendOutput(response, "{\"error\":\"Invalid test execution id.\"}");
        return;
    }

    try {

        String data = null;
        InputStream is = request.getInputStream();

        if (is != null) {
            try {
                StringBuilder sb = new StringBuilder();
                String line;
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                data = sb.toString();
            } finally {
                is.close();
            }

        }

        if (data == null) {
            sendOutput(response, "{\"error\":\"No data received.\"}");
            return;
        }

        final JSONObject info = new JSONObject(data);

        final Integer stepId = info.getInt("stepId");
        final String cluster = info.getJSONObject("cluster").toString();
        final String times = info.getJSONObject("times").toString();
        final JSONObject tagExecutionInfo = info.getJSONObject("tagExecutionInfo");

        int itemCount = 0;
        final Iterator keys = tagExecutionInfo.keys();
        while (keys.hasNext()) {
            final String cnt = (String) keys.next();
            final Integer tagCount = Integer.valueOf(cnt);
            TestStepExecution exec = this.testStepExecutionDao.selectTestStepExecution(executionId, stepId,
                    tagCount);

            if (exec != null) {
                sendOutput(response,
                        "{\"error\":\"This step has already been saved. Please contact an administrator.\"}");
                return;
            }

            final JSONObject itemInfo = tagExecutionInfo.getJSONObject(cnt);

            exec = new TestStepExecution();
            exec.setExecutionId(executionId);
            exec.setTagCount(tagCount);
            exec.setBaseEffort(itemInfo.getDouble("baseEffort"));
            exec.setBaseRelevantEffort(itemInfo.getDouble("baseRelevantEffort"));
            exec.setUserEffort(itemInfo.getDouble("userEffort"));
            exec.setCluster(cluster);
            exec.setTimes(times);
            exec.setStepId(stepId);
            exec.setTags(itemInfo.getJSONObject("tags").toString());

            if (this.isLoggedIn()) {
                exec.setUid(applicationUser.getUserId());
            }

            this.testStepExecutionDao.saveTestStepExecution(exec);
            itemCount++;
        }

        //if no tagged items
        if (itemCount == 0) {
            TestStepExecution exec = this.testStepExecutionDao.selectTestStepExecution(executionId, stepId, 0);

            if (exec != null) {
                sendOutput(response,
                        "{\"error\":\"This step has already been saved. Please contact an administrator.\"}");
                return;
            }

            exec = new TestStepExecution();
            exec.setExecutionId(executionId);
            exec.setTagCount(0);
            exec.setBaseEffort(0.0D);
            exec.setBaseRelevantEffort(0.0D);
            exec.setUserEffort(0.0D);
            exec.setCluster(cluster);
            exec.setTimes(times);
            exec.setStepId(stepId);
            exec.setTags("{}");

            if (this.isLoggedIn()) {
                exec.setUid(applicationUser.getUserId());
            }

            this.testStepExecutionDao.saveTestStepExecution(exec);
        }

        sendOutput(response, "{\"success\":true}");

    } catch (Exception e) {
        sendOutput(response, "{\"error\":" + JSONObject.quote(e.getMessage()) + "}");
        return;
    }

}

From source file:com.deployd.DeploydObject.java

public DeploydObject(JSONObject obj) {
    String k;// w w w.j  av a 2 s  .co  m
    while ((k = (String) obj.keys().next()) != NULL) {
        try {
            this.put(k, obj.get(k));
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}