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.yahoo.egads.data.JsonEncoder.java

public static void fromJson(Object object, JSONObject json_obj) throws Exception {
    // for each json key-value, that has a corresponding variable in object ...
    for (Iterator k = json_obj.keys(); k.hasNext();) {
        String key = (String) k.next();
        Object value = json_obj.get(key);

        // try to access object variable
        Field field = null;/*from w  w w.ja va2s .c o m*/
        try {
            field = object.getClass().getField(key);
        } catch (Exception e) {
            continue;
        }
        if (Modifier.isStatic(field.getModifiers())) {
            continue;
        }
        if (Modifier.isPrivate(field.getModifiers())) {
            continue;
        }
        Object member = field.get(object);

        if (json_obj.isNull(key)) {
            field.set(object, null);
            continue;
            // if variable is container... recurse
        } else if (member instanceof JsonAble) {
            ((JsonAble) member).fromJson((JSONObject) value);
            // if variable is an array... recurse on sub-objects
        } else if (member instanceof ArrayList) {
            // Depends on existance of ArrayList<T> template parameter, and T constructor with no arguments.
            // May be better to use custom fromJson() in member class.
            ArrayList memberArray = (ArrayList) member;
            JSONArray jsonArray = (JSONArray) value;

            // find array element constructor
            ParameterizedType arrayType = null;
            if (field.getGenericType() instanceof ParameterizedType) {
                arrayType = (ParameterizedType) field.getGenericType();
            }
            for (Class c = member.getClass(); arrayType == null && c != null; c = c.getSuperclass()) {
                if (c.getGenericSuperclass() instanceof ParameterizedType) {
                    arrayType = (ParameterizedType) c.getGenericSuperclass();
                }
            }
            if (arrayType == null) {
                throw new Exception("could not find ArrayList element type for field 'key'");
            }
            Class elementClass = (Class) (arrayType.getActualTypeArguments()[0]);
            Constructor elementConstructor = elementClass.getConstructor();

            // for each element in JSON array ... append element to member array, recursively decode element
            for (int i = 0; i < jsonArray.length(); ++i) {
                Object element = elementConstructor.newInstance();
                fromJson(element, jsonArray.getJSONObject(i));
                memberArray.add(element);
            }
            // if variable is simple value... set
        } else if (field.getType() == float.class) {
            field.set(object, (float) json_obj.getDouble(key));
        } else {
            field.set(object, value);
        }
    }
}

From source file:com.mirasense.scanditsdk.plugin.ScanditSDK.java

private void setOptionsOnBundle(JSONObject options, Bundle bundle) {
    @SuppressWarnings("unchecked")
    Iterator<String> iter = (Iterator<String>) options.keys();
    while (iter.hasNext()) {
        String key = iter.next();
        Object obj = options.opt(key);
        if (obj != null) {
            if (obj instanceof Float) {
                bundle.putFloat(key.toLowerCase(), (Float) obj);
            } else if (obj instanceof Double) {
                bundle.putDouble(key.toLowerCase(), (Double) obj);
            } else if (obj instanceof Integer) {
                bundle.putInt(key.toLowerCase(), (Integer) obj);
            } else if (obj instanceof Boolean) {
                bundle.putBoolean(key.toLowerCase(), (Boolean) obj);
            } else if (obj instanceof String) {
                bundle.putString(key.toLowerCase(), (String) obj);
            }// w w  w  .  j av  a 2s  . c  o m
        }
    }
}

From source file:com.jsonstore.api.JSONStoreAddOptions.java

/**
 * Add an additional search field for the add operation.
 * @param additional_search_fields//from  w ww .java  2 s  .  co m
 *             A JSONObject that contains key/value pairs for additional search fields.
 * @throws IllegalArgumentException
 *             Thrown if the additional_search_fields parameter is null or empty.
 */
public void addAdditionalSearchFields(JSONObject additional_search_fields) {
    if (additional_search_fields == null)
        additional_search_fields = new JSONObject();
    Iterator jsonObjectKeys = additional_search_fields.keys();
    while (jsonObjectKeys.hasNext()) {
        String key = (String) jsonObjectKeys.next();
        Object val = null;
        try {
            val = additional_search_fields.get(key);
        } catch (JSONException e) {
            throw new IllegalArgumentException(
                    "Error when adding additional search field. Could not get the value in JSONObject for search field '"
                            + key + "'.",
                    e);
        }

        putAdditionalSearchField(key, val);
    }
}

From source file:net.phase.wallet.Currency.java

private void updateBalanceFromUrl(String url) throws IOException, JSONException, java.text.ParseException {
    if (url.equals(emptyBaseUrl)) {
        Log.i("balance", "skipping URL " + url);
        return;//from w  w w.  j  a  v  a 2  s .  c  o m
    }

    Log.i("balance", "fetching URL " + url);
    HttpClient client = new DefaultHttpClient();
    HttpGet hg = new HttpGet(url);

    HttpResponse response = client.execute(hg);

    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        JSONObject resp = new JSONObject(EntityUtils.toString(response.getEntity()));

        // JSONObject.keys() returns Iterator<String> but for some reason
        // isn't typed that way
        @SuppressWarnings("unchecked")
        Iterator<String> itr = resp.keys();

        // look through every transaction
        while (itr.hasNext()) {
            JSONObject txObject = resp.getJSONObject(itr.next());
            String txHash = txObject.getString("hash");
            String inKeyHash = "unknown";

            // only process transaction if we haven't seen it before
            if (!transactionCache.contains(txHash)) {
                Log.i("balance", "Parsing txObject " + txHash);
                transactionCache.add(txHash);
                // find the in transaction
                JSONArray txsIn = txObject.getJSONArray("in");
                Date date = formatter.parse(txObject.getString("time"));

                for (int i = 0; i < txsIn.length(); i++) {
                    JSONObject inRecord = txsIn.getJSONObject(i);
                    try {
                        inKeyHash = inRecord.optString("address");

                        // if one of our keys is there, we are paying :(
                        if (Key.arrayContains(wallet.keys, inKeyHash)) {
                            JSONObject prevRecord = inRecord.getJSONObject("prev_out");
                            // if we paid for part of this transaction,
                            // record this.
                            pendingDebits.add(new prevout(txHash, prevRecord.getString("hash"),
                                    prevRecord.getInt("n"), date, inKeyHash));
                        }
                    } catch (JSONException e) {
                        // no address. Probably a generation transaction
                    }
                }

                // find the out transaction
                JSONArray txsOut = txObject.getJSONArray("out");

                for (int i = 0; i < txsOut.length(); i++) {
                    JSONObject outRecord = txsOut.getJSONObject(i);
                    String outKeyHash = outRecord.optString("address");
                    // convert to microbitcoins for accuracy
                    long value = (long) (outRecord.getDouble("value") * SATOSHIS_PER_BITCOIN);
                    // store the out transaction, this is used later on
                    txs.add(new tx(txHash, i, value, outKeyHash, inKeyHash));

                    // if one of our keys is there, add the balance
                    if (Key.arrayContains(wallet.keys, outKeyHash)) {
                        transactions.add(new Transaction(date, value, inKeyHash, outKeyHash));
                        balance += value;
                    }
                }
            }
        }
    } else {
        Log.e("wallet", "Got " + response.getStatusLine().getStatusCode() + " back from HTTP GET");
    }
}

From source file:com.norman0406.slimgress.API.Knobs.XMCostKnobs.java

public XMCostKnobs(JSONObject json) throws JSONException {
    super(json);//from  w w  w.java  2 s . co m

    mHeatsinkDeployCostByLevel = getIntArray(json, "heatsinkDeployCostByLevel");
    mFlipCardCostByLevel = getIntArray(json, "flipCardCostByLevel");
    mTurretDeployCostByLevel = getIntArray(json, "turretDeployCostByLevel");
    mPortalHackNeutralCostByLevel = getIntArray(json, "portalHackNeutralCostByLevel");
    mShieldDeployCostByLevel = getIntArray(json, "shieldDeployCostByLevel");
    mXmpFiringCostByLevel = getIntArray(json, "xmpFiringCostByLevel");
    mResonatorUpgradeCostByLevel = getIntArray(json, "resonatorUpgradeCostByLevel");
    mPortalHackFriendlyCostByLevel = getIntArray(json, "portalHackFriendlyCostByLevel");
    mMultihackDeployCostByLevel = getIntArray(json, "multihackDeployCostByLevel");
    mPortalHackEnemyCostByLevel = getIntArray(json, "portalHackEnemyCostByLevel");
    mResonatorDeployCostByLevel = getIntArray(json, "resonatorDeployCostByLevel");
    mForceAmplifierDeployCostByLevel = getIntArray(json, "forceAmplifierDeployCostByLevel");
    mLinkAmplifierDeployCostByLevel = getIntArray(json, "linkAmplifierDeployCostByLevel");

    mPortalModByLevel = new HashMap<String, List<Integer>>();
    JSONObject portalModByLevel = json.getJSONObject("portalModByLevel");
    Iterator<?> it = portalModByLevel.keys();
    while (it.hasNext()) {
        String key = (String) it.next();
        mPortalModByLevel.put(key, getIntArray(portalModByLevel, key));
    }
}

From source file:org.apache.cordova.filetransfer.FileTransfer.java

/**
 * Uploads the specified file to the server URL provided using an HTTP multipart request.
 * @param source        Full path of the file on the file system
 * @param target        URL of the server to receive the file
 * @param args          JSON Array of args
 * @param callbackContext    callback id for optional progress reports
 *
 * args[2] fileKey       Name of file request parameter
 * args[3] fileName      File name to be used on server
 * args[4] mimeType      Describes file content type
 * args[5] params        key:value pairs of user-defined parameters
 * @return FileUploadResult containing result of upload request
 *///from   ww  w  . jav a  2s  .  co m
private void upload(final String source, final String target, JSONArray args, CallbackContext callbackContext)
        throws JSONException {
    Log.d(LOG_TAG, "upload " + source + " to " + target);

    // Setup the options
    final String fileKey = getArgument(args, 2, "file");
    final String fileName = getArgument(args, 3, "image.jpg");
    final String mimeType = getArgument(args, 4, "image/jpeg");
    final JSONObject params = args.optJSONObject(5) == null ? new JSONObject() : args.optJSONObject(5);
    final boolean trustEveryone = args.optBoolean(6);
    // Always use chunked mode unless set to false as per API
    final boolean chunkedMode = args.optBoolean(7) || args.isNull(7);
    // Look for headers on the params map for backwards compatibility with older Cordova versions.
    final JSONObject headers = args.optJSONObject(8) == null ? params.optJSONObject("headers")
            : args.optJSONObject(8);
    final String objectId = args.getString(9);
    final String httpMethod = getArgument(args, 10, "POST");

    final CordovaResourceApi resourceApi = webView.getResourceApi();

    Log.d(LOG_TAG, "fileKey: " + fileKey);
    Log.d(LOG_TAG, "fileName: " + fileName);
    Log.d(LOG_TAG, "mimeType: " + mimeType);
    Log.d(LOG_TAG, "params: " + params);
    Log.d(LOG_TAG, "trustEveryone: " + trustEveryone);
    Log.d(LOG_TAG, "chunkedMode: " + chunkedMode);
    Log.d(LOG_TAG, "headers: " + headers);
    Log.d(LOG_TAG, "objectId: " + objectId);
    Log.d(LOG_TAG, "httpMethod: " + httpMethod);

    final Uri targetUri = resourceApi.remapUri(Uri.parse(target));
    // Accept a path or a URI for the source.
    Uri tmpSrc = Uri.parse(source);
    final Uri sourceUri = resourceApi
            .remapUri(tmpSrc.getScheme() != null ? tmpSrc : Uri.fromFile(new File(source)));

    int uriType = CordovaResourceApi.getUriType(targetUri);
    final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS;
    if (uriType != CordovaResourceApi.URI_TYPE_HTTP && !useHttps) {
        JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0, null);
        Log.e(LOG_TAG, "Unsupported URI: " + targetUri);
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
        return;
    }

    final RequestContext context = new RequestContext(source, target, callbackContext);
    synchronized (activeRequests) {
        activeRequests.put(objectId, context);
    }

    cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            if (context.aborted) {
                return;
            }
            HttpURLConnection conn = null;
            HostnameVerifier oldHostnameVerifier = null;
            SSLSocketFactory oldSocketFactory = null;
            int totalBytes = 0;
            int fixedLength = -1;
            try {
                // Create return object
                FileUploadResult result = new FileUploadResult();
                FileProgressResult progress = new FileProgressResult();

                //------------------ CLIENT REQUEST
                // Open a HTTP connection to the URL based on protocol
                conn = resourceApi.createHttpConnection(targetUri);
                if (useHttps && trustEveryone) {
                    // Setup the HTTPS connection class to trust everyone
                    HttpsURLConnection https = (HttpsURLConnection) conn;
                    oldSocketFactory = trustAllHosts(https);
                    // Save the current hostnameVerifier
                    oldHostnameVerifier = https.getHostnameVerifier();
                    // Setup the connection not to verify hostnames
                    https.setHostnameVerifier(DO_NOT_VERIFY);
                }

                // 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(httpMethod);

                // if we specified a Content-Type header, don't do multipart form upload
                boolean multipartFormUpload = (headers == null) || !headers.has("Content-Type");
                if (multipartFormUpload) {
                    conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
                }

                // Set the cookies on the response
                String cookie = getCookies(target);

                if (cookie != null) {
                    conn.setRequestProperty("Cookie", cookie);
                }

                // Handle the other headers
                if (headers != null) {
                    addHeadersToRequest(conn, headers);
                }

                /*
                * Store the non-file portions of the multipart data as a string, so that we can add it
                * to the contentSize, since it is part of the body of the HTTP request.
                */
                StringBuilder beforeData = new StringBuilder();
                try {
                    for (Iterator<?> iter = params.keys(); iter.hasNext();) {
                        Object key = iter.next();
                        if (!String.valueOf(key).equals("headers")) {
                            beforeData.append(LINE_START).append(BOUNDARY).append(LINE_END);
                            beforeData.append("Content-Disposition: form-data; name=\"").append(key.toString())
                                    .append('"');
                            beforeData.append(LINE_END).append(LINE_END);
                            beforeData.append(params.getString(key.toString()));
                            beforeData.append(LINE_END);
                        }
                    }
                } catch (JSONException e) {
                    Log.e(LOG_TAG, e.getMessage(), e);
                }

                beforeData.append(LINE_START).append(BOUNDARY).append(LINE_END);
                beforeData.append("Content-Disposition: form-data; name=\"").append(fileKey).append("\";");
                beforeData.append(" filename=\"").append(fileName).append('"').append(LINE_END);
                beforeData.append("Content-Type: ").append(mimeType).append(LINE_END).append(LINE_END);
                byte[] beforeDataBytes = beforeData.toString().getBytes("UTF-8");
                byte[] tailParamsBytes = (LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END)
                        .getBytes("UTF-8");

                // Get a input stream of the file on the phone
                OpenForReadResult readResult = resourceApi.openForRead(sourceUri);

                int stringLength = beforeDataBytes.length + tailParamsBytes.length;
                if (readResult.length >= 0) {
                    fixedLength = (int) readResult.length;
                    if (multipartFormUpload)
                        fixedLength += stringLength;
                    progress.setLengthComputable(true);
                    progress.setTotal(fixedLength);
                }
                Log.d(LOG_TAG, "Content Length: " + fixedLength);
                // setFixedLengthStreamingMode causes and OutOfMemoryException on pre-Froyo devices.
                // http://code.google.com/p/android/issues/detail?id=3164
                // It also causes OOM if HTTPS is used, even on newer devices.
                boolean useChunkedMode = chunkedMode
                        && (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO || useHttps);
                useChunkedMode = useChunkedMode || (fixedLength == -1);

                if (useChunkedMode) {
                    conn.setChunkedStreamingMode(MAX_BUFFER_SIZE);
                    // Although setChunkedStreamingMode sets this header, setting it explicitly here works
                    // around an OutOfMemoryException when using https.
                    conn.setRequestProperty("Transfer-Encoding", "chunked");
                } else {
                    conn.setFixedLengthStreamingMode(fixedLength);
                }

                conn.connect();

                OutputStream sendStream = null;
                try {
                    sendStream = conn.getOutputStream();
                    synchronized (context) {
                        if (context.aborted) {
                            return;
                        }
                        context.connection = conn;
                    }

                    if (multipartFormUpload) {
                        //We don't want to change encoding, we just want this to write for all Unicode.
                        sendStream.write(beforeDataBytes);
                        totalBytes += beforeDataBytes.length;
                    }

                    // create a buffer of maximum size
                    int bytesAvailable = readResult.inputStream.available();
                    int bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE);
                    byte[] buffer = new byte[bufferSize];

                    // read file and write it into form...
                    int bytesRead = readResult.inputStream.read(buffer, 0, bufferSize);

                    long prevBytesRead = 0;
                    while (bytesRead > 0) {
                        result.setBytesSent(totalBytes);
                        sendStream.write(buffer, 0, bytesRead);
                        totalBytes += bytesRead;
                        if (totalBytes > prevBytesRead + 102400) {
                            prevBytesRead = totalBytes;
                            Log.d(LOG_TAG, "Uploaded " + totalBytes + " of " + fixedLength + " bytes");
                        }
                        bytesAvailable = readResult.inputStream.available();
                        bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE);
                        bytesRead = readResult.inputStream.read(buffer, 0, bufferSize);

                        // Send a progress event.
                        progress.setLoaded(totalBytes);
                        PluginResult progressResult = new PluginResult(PluginResult.Status.OK,
                                progress.toJSONObject());
                        progressResult.setKeepCallback(true);
                        context.sendPluginResult(progressResult);
                    }

                    if (multipartFormUpload) {
                        // send multipart form data necessary after file data...
                        sendStream.write(tailParamsBytes);
                        totalBytes += tailParamsBytes.length;
                    }
                    sendStream.flush();
                } finally {
                    safeClose(readResult.inputStream);
                    safeClose(sendStream);
                }
                synchronized (context) {
                    context.connection = null;
                }
                Log.d(LOG_TAG, "Sent " + totalBytes + " of " + fixedLength);

                //------------------ read the SERVER RESPONSE
                String responseString;
                int responseCode = conn.getResponseCode();
                Log.d(LOG_TAG, "response code: " + responseCode);
                Log.d(LOG_TAG, "response headers: " + conn.getHeaderFields());
                TrackingInputStream inStream = null;
                try {
                    inStream = getInputStream(conn);
                    synchronized (context) {
                        if (context.aborted) {
                            return;
                        }
                        context.connection = conn;
                    }

                    ByteArrayOutputStream out = new ByteArrayOutputStream(
                            Math.max(1024, conn.getContentLength()));
                    byte[] buffer = new byte[1024];
                    int bytesRead = 0;
                    // write bytes to file
                    while ((bytesRead = inStream.read(buffer)) > 0) {
                        out.write(buffer, 0, bytesRead);
                    }
                    responseString = out.toString("UTF-8");
                } finally {
                    synchronized (context) {
                        context.connection = null;
                    }
                    safeClose(inStream);
                }

                Log.d(LOG_TAG, "got response from server");
                Log.d(LOG_TAG, responseString.substring(0, Math.min(256, responseString.length())));

                // send request and retrieve response
                result.setResponseCode(responseCode);
                result.setResponse(responseString);

                context.sendPluginResult(new PluginResult(PluginResult.Status.OK, result.toJSONObject()));
            } catch (FileNotFoundException e) {
                JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn, e);
                Log.e(LOG_TAG, error.toString(), e);
                context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
            } catch (IOException e) {
                JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn, e);
                Log.e(LOG_TAG, error.toString(), e);
                Log.e(LOG_TAG, "Failed after uploading " + totalBytes + " of " + fixedLength + " bytes.");
                context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
            } catch (JSONException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
                context.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
            } catch (Throwable t) {
                // Shouldn't happen, but will
                JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn, t);
                Log.e(LOG_TAG, error.toString(), t);
                context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
            } finally {
                synchronized (activeRequests) {
                    activeRequests.remove(objectId);
                }

                if (conn != null) {
                    // Revert back to the proper verifier and socket factories
                    // Revert back to the proper verifier and socket factories
                    if (trustEveryone && useHttps) {
                        HttpsURLConnection https = (HttpsURLConnection) conn;
                        https.setHostnameVerifier(oldHostnameVerifier);
                        https.setSSLSocketFactory(oldSocketFactory);
                    }
                }
            }
        }
    });
}

From source file:org.collectionspace.chain.csp.webui.record.RecordRead.java

private JSONArray getPermissions(Storage storage, JSONObject activePermissionInfo)
        throws ExistException, UnimplementedException, UnderlyingStorageException, JSONException, UIException {
    final String WORKFLOW_DELETE_RESOURCE_TAIL = WORKFLOW_SUB_RESOURCE + "delete";
    final String WORKFLOW_LOCK_RESOURCE_TAIL = WORKFLOW_SUB_RESOURCE + "lock";

    JSONArray set = new JSONArray();
    JSONObject activePermissions = new JSONObject();

    //log.info(activePermissionInfo.toString());
    //we are ignoring pagination so this will return the first 40 roles only
    //UI doesn't know what it wants to do about pagination etc
    //mark active roles
    if (activePermissionInfo.has("permission")) {
        JSONArray active = activePermissionInfo.getJSONArray("permission");
        for (int j = 0; j < active.length(); j++) {
            if (active.getJSONObject(j).length() != 0) {
                activePermissions.put(active.getJSONObject(j).getString("resourceName"),
                        active.getJSONObject(j));
            }/*from w w  w .java  2 s .co m*/
        }
    }

    JSONObject mergedPermissions = new JSONObject();

    //get all permissions
    int pageNum = 0;
    JSONObject permrestrictions = new JSONObject();
    permrestrictions.put("queryTerm", "actGrp");
    permrestrictions.put("queryString", "CRUDL");
    // Passing page size 0 gets all the perms in one call.
    permrestrictions.put("pageSize", Integer.toString(pageNum));
    String permbase = spec.getRecordByWebUrl("permission").getID();
    JSONObject returndata = searcher.getJSON(storage, permrestrictions, "items", permbase);

    // While loop since perms do not return pagination info - must call till no more
    //while(returndata.has("items") && returndata.getJSONArray("items").length()>0){
    // Using pageSize=0, we get all perms in one call, so no need to loop
    if (returndata.has("items") && returndata.getJSONArray("items").length() > 0) {

        //merge active and nonactive
        JSONArray items = returndata.getJSONArray("items");
        for (int i = 0; i < items.length(); i++) {
            JSONObject item = items.getJSONObject(i);
            JSONObject permission = new JSONObject();
            String resourceName = item.getString("summary");
            String resourceNameUI;
            // Need to get baseResource for workflow perms
            int startWorkflowSubResource = resourceName.indexOf(WORKFLOW_SUB_RESOURCE);
            if (startWorkflowSubResource > 0) { // Contains the workflow subresource     
                // Get the base resource that the workflow is related to
                int start = (resourceName.startsWith("/")) ? 1 : 0;
                String baseResource = resourceName.substring(start, startWorkflowSubResource);
                resourceNameUI = Generic.ResourceNameUI(spec, baseResource);
            } else {
                resourceNameUI = Generic.ResourceNameUI(spec, resourceName);
            }
            permission.put("resourceName", resourceNameUI);
            String permlevel = "none";

            Record recordForPermResource = Generic.RecordNameServices(spec, resourceNameUI);

            if ((startWorkflowSubResource > 0) && (recordForPermResource != null)) {
                // Handle the lock workflow resource
                if (recordForPermResource.supportsLocking() && resourceName.endsWith("lock")
                        && activePermissions.has(resourceName) && Generic.PermissionIncludesWritable(
                                activePermissions.getJSONObject(resourceName).getString("actionGroup"))) {
                    // If we have write or delete perms on the workflow resource, set the permLevel
                    // on the base resource.
                    // Should be, but UI not ready: permission.put("permission", Generic.LOCK_PERMISSION);
                    if (!mergedPermissions.has(resourceNameUI)) {
                        // With no other knowledge, assume lock perm means writable
                        permission.put("permission", Generic.WRITE_PERMISSION);
                        mergedPermissions.put(resourceNameUI, permission);
                    } else {
                        // We could check it and make sure it makes sense, but we have to trust that the UI has
                        // done something reasonable by not combining lock perm with read-only or other silliness.
                    }
                }
                // Handle the delete workflow resource
                else if (recordForPermResource.hasSoftDeleteMethod() && resourceName.endsWith("delete")
                        && activePermissions.has(resourceName) && Generic.PermissionIncludesWritable(
                                activePermissions.getJSONObject(resourceName).getString("actionGroup"))) {
                    // If we have write or delete perms on the workflow resource, set the permLevel
                    // on the base resource.
                    permission.put("permission", Generic.DELETE_PERMISSION);
                    mergedPermissions.put(resourceNameUI, permission);
                } else {
                    // Filter these out - no need to model them, as we do not support them
                    // This is a performance improvement so we do not have to handle them on
                    // update.
                }
            } else if (activePermissions.has(resourceName) && !mergedPermissions.has(resourceNameUI)) {
                permlevel = Generic.PermissionLevelString(
                        activePermissions.getJSONObject(resourceName).getString("actionGroup"));

                permission.put("permission", permlevel);
                mergedPermissions.put(resourceNameUI, permission);
            } else if (!mergedPermissions.has(resourceNameUI)) {
                permlevel = "none";

                permission.put("permission", permlevel);
                mergedPermissions.put(resourceNameUI, permission);
            }
        }

        //pageNum++;
        //permrestrictions.put("pageNum", Integer.toString(pageNum));
        //returndata = searcher.getJSON(storage,permrestrictions,"items",permbase);
    }

    //change soft workflow to main Delete

    //now put the permissions in order...
    String[] recordsweburl = spec.getAllRecordsOrdered();

    for (String weburl : recordsweburl) {
        if (mergedPermissions.has(weburl)) {
            Object value = mergedPermissions.get(weburl);
            set.put(value);
        }
    }
    Iterator rit = mergedPermissions.keys();
    while (rit.hasNext()) {
        String key = (String) rit.next();
        Object value = mergedPermissions.get(key);

        if (!spec.hasRecordByWebUrl(key)) {
            set.put(value);
        }
    }

    return set;
}

From source file:org.jbpm.designer.server.diagram.DiagramBuilder.java

/**
 * create a HashMap form the json properties and add it to the shape
 * /*w  w  w  . j a  va  2  s.  c  o  m*/
 * @param modelJSON
 * @param current
 * @throws org.json.JSONException
 */
@SuppressWarnings("unchecked")
private static void parseProperties(JSONObject modelJSON, Shape current, Boolean keepGlossaryLink)
        throws JSONException {
    if (modelJSON.has("properties")) {
        JSONObject propsObject = modelJSON.getJSONObject("properties");
        Iterator<String> keys = propsObject.keys();
        Pattern pattern = Pattern.compile(jsonPattern);

        while (keys.hasNext()) {
            StringBuilder result = new StringBuilder();
            int lastIndex = 0;
            String key = keys.next();
            String value = propsObject.getString(key);

            if (!keepGlossaryLink) {
                Matcher matcher = pattern.matcher(value);
                while (matcher.find()) {
                    String id = matcher.group(1);
                    current.addGlossaryIds(id);
                    String text = matcher.group(2);
                    result.append(text);
                    lastIndex = matcher.end();
                }
                result.append(value.substring(lastIndex));
                value = result.toString();
            }

            current.putProperty(key, value);
        }
    }
}

From source file:net.openwatch.acluaz.fragment.FormFragment.java

public void writeJsonToPrefs(final String prefs_name, final JSONObject json) {
    final Context c = this.getActivity();
    new Thread(new Runnable() {

        @Override//w ww .j av  a2 s . co m
        public void run() {
            Iterator<?> keys = json.keys();
            SharedPreferences.Editor prefs = c.getSharedPreferences(prefs_name, c.MODE_PRIVATE).edit();
            String key;
            while (keys.hasNext()) {
                key = (String) keys.next();
                try {
                    prefs.putString(key, json.get(key).toString());
                } catch (JSONException e) {
                    Log.e(TAG, "Error writing json to prefs. JSON: " + json.toString());
                    e.printStackTrace();
                }
            }
            prefs.commit();

        }

    }).start();
}

From source file:com.purplefrog.glitchclocka.LearningReadout.java

public void handleJSONResponse(JSONObject json) {
    JSONObject learning_ = json.optJSONObject("learning");

    if (learning_ == null) {
        learningState = new LearningState("nothing", System.currentTimeMillis() / 1000, 0, "",
                "you're not learnin' nuthin.");
        updateReadoutFull();//from   w  w w .j a  v a2 s .c o  m
        return;
    }

    String skillId = learning_.keys().next().toString();
    JSONObject learning = learning_.optJSONObject(skillId);

    String name = learning.optString("name");
    long timeComplete = learning.optLong("time_complete");
    int totalTime = learning.optInt("total_time");
    String skillIconURL = learning.optString("icon_100");
    String description = learning.optString("description");

    learningState = new LearningState(name, timeComplete, totalTime, skillIconURL, description);
    updateReadoutFull();

    final String partial = name + " " + timeComplete + " " + totalTime + " " + skillIconURL + " \n"
            + description;

    debugText.setText(partial + "\n\n" + json);
}