Example usage for org.json JSONObject has

List of usage examples for org.json JSONObject has

Introduction

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

Prototype

public boolean has(String key) 

Source Link

Document

Determine if the JSONObject contains a specific key.

Usage

From source file:ai.susi.mind.SusiThought.java

/**
 * All details of the creation of this thought is collected in a metadata statement.
 * @return the set of meta information for this thought
 *//*from  w w w .ja v  a2  s .  co m*/
private JSONObject getMetadata() {
    JSONObject md;
    if (this.has(metadata_name))
        md = this.getJSONObject(metadata_name);
    else {
        md = new JSONObject();
        this.put(metadata_name, md);
    }
    if (!md.has("count"))
        md.put("count", getData().length());
    return md;
}

From source file:ai.susi.mind.SusiThought.java

private final static boolean anyObjectKeySame(final JSONObject a, final JSONObject b) {
    for (String k : a.keySet())
        if (b.has(k))
            return true;
    return false;
}

From source file:ai.susi.mind.SusiThought.java

/**
 * If during thinking we observe something that we want to memorize, we can memorize this here.
 * We insert the new data always in front of existing same data to make it visible as primary
 * backtracking option. This means that new observations are always more important than old
 * observations but do not overwrite them; they can be used again in case that the new observation
 * is not valid during inference computation.
 * @param featureName the object key/*w  w  w.j av  a2 s . c o  m*/
 * @param observation the object value
 * @return the thought
 */
public SusiThought addObservation(String featureName, String observation) {
    JSONArray data = getData();

    // find first occurrence of key in rows
    int rowc = 0;
    boolean found = false;
    while (rowc < data.length()) {
        JSONObject row = data.getJSONObject(rowc);
        if (row.has(featureName))
            found = true;
        if (found)
            break;
        rowc++;
    }
    if (found) {
        // insert feature in front of row
        if (rowc == 0) {
            // insert a row and shift everything up
            JSONArray newData = new JSONArray();
            JSONObject row = new JSONObject();
            row.put(featureName, observation);
            newData.put(row);
            for (Object o : data)
                newData.put(o);
            this.setData(newData);
        } else {
            JSONObject row = data.getJSONObject(rowc - 1);
            row.put(featureName, observation);
        }
    } else {
        // insert into first line
        if (data.length() == 0) {
            JSONObject row = new JSONObject();
            row.put(featureName, observation);
            data.put(row);
        } else {
            JSONObject row = data.getJSONObject(0);
            row.put(featureName, observation);
        }
    }
    return this;
}

From source file:com.funzio.pure2D.particles.nova.vo.NovaParticleVO.java

public NovaParticleVO(final JSONObject json) throws JSONException {
    super(json);/*from   w  w  w .j  a v a2 s . c o m*/

    name = json.optString("name");

    if (json.has("start_delay")) {
        start_delay = json.getInt("start_delay");
    }

    if (json.has("step_delay")) {
        step_delay = json.getInt("step_delay");
    }

    if (json.has("duration")) {
        duration = json.getInt("duration");
    }

    if (json.has("step_quantity")) {
        step_quantity = json.getInt("step_quantity");
    }

    if (json.has("layer")) {
        layer = json.getInt("layer");
    }

    if (json.has("origin_x")) {
        origin_x = json.getInt("origin_x");
    }

    if (json.has("origin_y")) {
        origin_y = json.getInt("origin_y");
    }

    // optional sprite or clip
    sprite = NovaVO.getListString(json, "sprite");
    start_frame = NovaVO.getListInt(json, "start_frame");
    loop_mode = NovaVO.getListString(json, "loop_mode");

    // basic DisplayObject's properties
    x = NovaVO.getListInt(json, "x");
    y = NovaVO.getListInt(json, "y");
    z = NovaVO.getListFloat(json, "z");
    animator = NovaVO.getListString(json, "animator");
    blend_mode = NovaVO.getListString(json, "blend_mode");
    alpha = NovaVO.getListFloat(json, "alpha");
    color = NovaVO.getListColor(json, "color");
    rotation = NovaVO.getListFloat(json, "rotation");
    scale_x = NovaVO.getListFloat(json, "scale_x");
    scale_y = NovaVO.getListFloat(json, "scale_y");
    skew_x = NovaVO.getListFloat(json, "skew_x");
    skew_y = NovaVO.getListFloat(json, "skew_y");
    motion_trail = NovaVO.getListString(json, "motion_trail");
}

From source file:jfabrix101.billing.BillingSecurity.java

/**
 * Verifies that the data was signed with the given signature, and returns
 * the list of verified purchases. The data is in JSON format and contains
 * a nonce (number used once) that we generated and that was signed
 * (as part of the whole data string) with a private key. The data also
 * contains the {@link PurchaseState} and product ID of the purchase.
 * In the general case, there can be an array of purchase transactions
 * because there may be delays in processing the purchase on the backend
 * and then several purchases can be batched together.
 * @param signedData the signed JSON string (signed, not encrypted)
 * @param signature the signature for the data, signed with the private key
 *///w ww .j  a  v a2s.  c  om
public static ArrayList<VerifiedPurchase> verifyPurchase(Context context, String signedData, String signature) {
    if (signedData == null) {
        Log.e(TAG, "data is null");
        return null;
    }
    if (BillingConsts.DEBUG) {
        Log.i(TAG, "signedData: " + signedData);
    }
    boolean verified = false;
    if (!TextUtils.isEmpty(signature)) {
        /**
         * Compute your public key (that you got from the Android Market publisher site).
         *
         * Instead of just storing the entire literal string here embedded in the
         * program,  construct the key at runtime from pieces or
         * use bit manipulation (for example, XOR with some other string) to hide
         * the actual key.  The key itself is not secret information, but we don't
         * want to make it easy for an adversary to replace the public key with one
         * of their own and then fake messages from the server.
         *
         * Generally, encryption keys / passwords should only be kept in memory
         * long enough to perform the operation they need to perform.
         */

        SharedPreferences pref = context.getSharedPreferences("billingPK", 0);
        AESObfuscator obfuscator = AESObfuscator.getDefaultObfuscator(context);
        String publicKey = "";
        try {
            publicKey = obfuscator.unobfuscate(pref.getString("pk", ""));
        } catch (Exception e) {
            Log.e(TAG, "Error getting publicc key from repository");
            return null;
        }
        PublicKey key = BillingSecurity.generatePublicKey(publicKey);
        verified = BillingSecurity.verify(key, signedData, signature);
        if (!verified) {
            Log.w(TAG, "signature does not match data.");
            return null;
        }
    }

    JSONObject jObject;
    JSONArray jTransactionsArray = null;
    int numTransactions = 0;
    long nonce = 0L;
    try {
        jObject = new JSONObject(signedData);

        // The nonce might be null if the user backed out of the buy page.
        nonce = jObject.optLong("nonce");
        jTransactionsArray = jObject.optJSONArray("orders");
        if (jTransactionsArray != null) {
            numTransactions = jTransactionsArray.length();
        }
    } catch (JSONException e) {
        return null;
    }

    if (!BillingSecurity.isNonceKnown(nonce)) {
        Log.w(TAG, "Nonce not found: " + nonce);
        return null;
    }

    ArrayList<VerifiedPurchase> purchases = new ArrayList<VerifiedPurchase>();
    try {
        for (int i = 0; i < numTransactions; i++) {
            JSONObject jElement = jTransactionsArray.getJSONObject(i);
            int response = jElement.getInt("purchaseState");
            PurchaseState purchaseState = PurchaseState.valueOf(response);
            String productId = jElement.getString("productId");
            //String packageName = jElement.getString("packageName");
            long purchaseTime = jElement.getLong("purchaseTime");
            String orderId = jElement.optString("orderId", "");
            String notifyId = null;
            if (jElement.has("notificationId")) {
                notifyId = jElement.getString("notificationId");
            }
            String developerPayload = jElement.optString("developerPayload", null);

            // If the purchase state is PURCHASED, then we require a verified nonce.
            if (purchaseState == PurchaseState.PURCHASED && !verified) {
                continue;
            }
            purchases.add(new VerifiedPurchase(purchaseState, notifyId, productId, orderId, purchaseTime,
                    developerPayload));
        }
    } catch (JSONException e) {
        Log.e(TAG, "JSON exception: ", e);
        return null;
    }
    removeNonce(nonce);
    return purchases;
}

From source file:com.krayzk9s.imgurholo.ui.AccountFragment.java

public void onGetObject(Object data, String tag) {
    refreshedCount++;/*from  w w  w .jav  a  2 s .  c  o m*/
    if (refreshedCount == 5) {
        mPullToRefreshLayout.setRefreshComplete();
    }
    try {
        if (data == null) {
            return;
        }
        JSONObject jsonData;

        /*int duration = Toast.LENGTH_SHORT;
            Toast toast;
        MainActivity activity = (MainActivity) getActivity();
        toast = Toast.makeText(activity, "User not found", duration);
        toast.show();
        activity.getFragmentManager().popBackStack();*/

        if (tag.equals(ACCOUNTDATA)) {
            jsonData = ((JSONObject) data).getJSONObject("data");
            if (jsonData.has("error"))
                return;
            Calendar accountCreationDate = Calendar.getInstance();
            accountCreationDate.setTimeInMillis((long) jsonData.getInt("created") * 1000);
            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
            String accountcreated = sdf.format(accountCreationDate.getTime());
            created.setText(accountcreated);
            reputation.setText(Integer.toString(jsonData.getInt("reputation")));
            if (jsonData.getString("bio") != null && !jsonData.getString("bio").equals("null")
                    && !jsonData.getString("bio").equals(""))
                biography.setText(jsonData.getString("bio"));
            else
                biography.setText("No Biography");
        } else if (tag.equals(COUNTDATA)) {
            jsonData = ((JSONObject) data);
            if (jsonData.has("error"))
                return;
            if (jsonData.getInt("status") == 200)
                mMenuList[1] = mMenuList[1] + " (" + Integer.toString(jsonData.getInt("data")) + ")";
            else
                mMenuList[1] = mMenuList[1] + " (0)";
        } else if (tag.equals(ALBUMDATA)) {
            jsonData = ((JSONObject) data);
            if (jsonData.has("error"))
                return;
            if (jsonData.getInt("status") == 200)
                mMenuList[0] = mMenuList[0] + " (" + Integer.toString(jsonData.getJSONArray("data").length())
                        + ")";
            else
                mMenuList[0] = mMenuList[0] + " (0)";
        } else if (tag.equals(LIKEDATA)) {
            JSONArray jsonArray = ((JSONObject) data).getJSONArray("data");
            mMenuList[2] = mMenuList[2] + " (" + String.valueOf(jsonArray.length()) + ")";
        } else if (tag.equals(COMMENTDATA)) {
            jsonData = ((JSONObject) data);
            mMenuList[3] = mMenuList[3] + " (" + String.valueOf(jsonData.getInt("data")) + ")";
        }
        adapter.notifyDataSetChanged();
    } catch (JSONException e) {
        Log.e("Error!", e.toString());
    }
}

From source file:vOS.controller.socket.IOConnection.java

/**
 * Transport message. {@link IOTransport} calls this, when a message has
 * been received./* ww w  . ja  v a2 s  . co  m*/
 * 
 * @param text
 *            the text
 */
public void transportMessage(String text) {
    logger.info("< " + text);
    IOMessage message;
    try {
        message = new IOMessage(text);
    } catch (Exception e) {
        error(new SocketIOException("Garbage from server: " + text, e));
        return;
    }
    resetTimeout();
    switch (message.getType()) {
    case IOMessage.TYPE_DISCONNECT:
        try {
            findCallback(message).onDisconnect();
        } catch (Exception e) {
            error(new SocketIOException("Exception was thrown in onDisconnect()", e));
        }
        break;
    case IOMessage.TYPE_CONNECT:
        try {
            if (firstSocket != null && "".equals(message.getEndpoint())) {
                if (firstSocket.getNamespace().equals("")) {
                    firstSocket.getCallback().onConnect();
                } else {
                    IOMessage connect = new IOMessage(IOMessage.TYPE_CONNECT, firstSocket.getNamespace(), "");
                    sendPlain(connect.toString());
                }
            } else {
                findCallback(message).onConnect();
            }
            firstSocket = null;
        } catch (Exception e) {
            error(new SocketIOException("Exception was thrown in onConnect()", e));
        }
        break;
    case IOMessage.TYPE_HEARTBEAT:
        sendPlain("2::");
        break;
    case IOMessage.TYPE_MESSAGE:
        try {
            findCallback(message).onMessage(message.getData(), remoteAcknowledge(message));
        } catch (Exception e) {
            error(new SocketIOException(
                    "Exception was thrown in onMessage(String).\n" + "Message was: " + message.toString(), e));
        }
        break;
    case IOMessage.TYPE_JSON_MESSAGE:
        try {
            JSONObject obj = null;
            String data = message.getData();
            if (data.trim().equals("null") == false)
                obj = new JSONObject(data);
            try {
                findCallback(message).onMessage(obj, remoteAcknowledge(message));
            } catch (Exception e) {
                error(new SocketIOException("Exception was thrown in onMessage(JSONObject).\n" + "Message was: "
                        + message.toString(), e));
            }
        } catch (JSONException e) {
            logger.warning("Malformated JSON received");
        }
        break;
    case IOMessage.TYPE_EVENT:
        try {
            JSONObject event = new JSONObject(message.getData());
            Object[] argsArray;
            if (event.has("args")) {
                JSONArray args = event.getJSONArray("args");
                argsArray = new Object[args.length()];
                for (int i = 0; i < args.length(); i++) {
                    if (args.isNull(i) == false)
                        argsArray[i] = args.get(i);
                }
            } else
                argsArray = new Object[0];
            String eventName = event.getString("name");
            try {
                findCallback(message).on(eventName, remoteAcknowledge(message), argsArray);
            } catch (Exception e) {
                error(new SocketIOException("Exception was thrown in on(String, JSONObject[]).\n"
                        + "Message was: " + message.toString(), e));
            }
        } catch (JSONException e) {
            logger.warning("Malformated JSON received");
        }
        break;

    case IOMessage.TYPE_ACK:
        String[] data = message.getData().split("\\+", 2);
        if (data.length == 2) {
            try {
                int id = Integer.parseInt(data[0]);
                IOAcknowledge ack = acknowledge.get(id);
                if (ack == null)
                    logger.warning("Received unknown ack packet");
                else {
                    JSONArray array = new JSONArray(data[1]);
                    Object[] args = new Object[array.length()];
                    for (int i = 0; i < args.length; i++) {
                        args[i] = array.get(i);
                    }
                    ack.ack(args);
                }
            } catch (NumberFormatException e) {
                logger.warning(
                        "Received malformated Acknowledge! This is potentially filling up the acknowledges!");
            } catch (JSONException e) {
                logger.warning("Received malformated Acknowledge data!");
            }
        } else if (data.length == 1) {
            sendPlain("6:::" + data[0]);
        }
        break;
    case IOMessage.TYPE_ERROR:
        try {
            findCallback(message).onError(new SocketIOException(message.getData()));
        } catch (SocketIOException e) {
            error(e);
        }
        if (message.getData().endsWith("+0")) {
            // We are advised to disconnect
            cleanup();
        }
        break;
    case IOMessage.TYPE_NOOP:
        break;
    default:
        logger.warning("Unkown type received" + message.getType());
        break;
    }
}

From source file:com.imaginary.home.cloud.device.Light.java

static void mapLight(@Nonnull ControllerRelay relay, @Nonnull JSONObject json,
        @Nonnull Map<String, Object> state) throws JSONException {
    mapPoweredDevice(relay, json, state);
    state.put("deviceType", "light");
    if (json.has("color")) {
        JSONObject color = json.getJSONObject("color");
        ColorMode colorMode = null;// w ww .  ja  v  a2 s. c om
        float[] components = null;

        if (color.has("colorMode") && !color.isNull("colorMode")) {
            try {
                colorMode = ColorMode.valueOf(color.getString("colorMode"));
            } catch (IllegalArgumentException e) {
                throw new JSONException("Invalid color mode: " + color.getString("colorMode"));
            }
        }
        if (color.has("components") && !color.isNull("components")) {
            JSONArray arr = color.getJSONArray("components");
            components = new float[arr.length()];

            for (int i = 0; i < arr.length(); i++) {
                components[i] = (float) arr.getDouble(i);
            }
        }
        if (colorMode != null || components != null) {
            state.put("colorMode", colorMode);
            state.put("colorValues", components);
        }
    }
    if (json.has("brightness") && !json.isNull("brightness")) {
        state.put("brightness", (float) json.getDouble("brightness"));
    }
    if (json.has("supportsColorChanges")) {
        state.put("colorChangeSupported",
                !json.isNull("supportsColorChanges") && json.getBoolean("supportsColorChanges"));
    }
    if (json.has("supportsBrightnessChanges")) {
        state.put("dimmable",
                !json.isNull("supportsBrightnessChanges") && json.getBoolean("supportsBrightnessChanges"));
    }
    if (json.has("colorModes")) {
        JSONArray arr = json.getJSONArray("colorModes");
        ColorMode[] modes = new ColorMode[arr.length()];

        for (int i = 0; i < arr.length(); i++) {
            try {
                modes[i] = ColorMode.valueOf(arr.getString(i));
            } catch (IllegalArgumentException e) {
                throw new JSONException("Invalid color mode: " + arr.getString(i));
            }
        }
        state.put("colorModesSupported", modes);
    }
}

From source file:com.basetechnology.s0.agentserver.field.FloatField.java

public static Field fromJson(SymbolTable symbolTable, JSONObject fieldJson) {
    String type = fieldJson.optString("type");
    if (type == null || !type.equals("float"))
        return null;
    String name = fieldJson.has("name") ? fieldJson.optString("name") : null;
    String label = fieldJson.has("label") ? fieldJson.optString("label") : null;
    String description = fieldJson.has("description") ? fieldJson.optString("description") : null;
    double defaultValue = fieldJson.has("default_value") ? fieldJson.optDouble("default_value") : 0;
    double minValue = fieldJson.has("min_value") ? fieldJson.optDouble("min_value") : Double.MIN_VALUE;
    double maxValue = fieldJson.has("max_value") ? fieldJson.optDouble("max_value") : Double.MAX_VALUE;
    int nominalWidth = fieldJson.has("nominal_width") ? fieldJson.optInt("nominal_width") : 0;
    String compute = fieldJson.has("compute") ? fieldJson.optString("compute") : null;
    return new FloatField(symbolTable, name, label, description, defaultValue, minValue, maxValue, nominalWidth,
            compute);//from w w  w .  ja v a 2  s  .c o  m
}

From source file:org.eclipse.orion.internal.server.servlets.xfer.TransferResourceDecorator.java

private void addTransferLinks(HttpServletRequest request, URI resource, JSONObject representation)
        throws URISyntaxException, JSONException, UnsupportedEncodingException {
    URI location = new URI(representation.getString(ProtocolConstants.KEY_LOCATION));
    IPath targetPath = new Path(location.getPath()).removeFirstSegments(1).removeTrailingSeparator();
    IPath path = new Path("/xfer/import").append(targetPath); //$NON-NLS-1$
    URI link = new URI(resource.getScheme(), resource.getAuthority(), path.toString(), null, null);
    if (representation.has(ProtocolConstants.KEY_EXCLUDED_IN_IMPORT)) {
        String linkString = link.toString();
        if (linkString.contains("?")) {
            linkString += "&" + ProtocolConstants.PARAM_EXCLUDE + "=" + URLEncoder
                    .encode(representation.getString(ProtocolConstants.KEY_EXCLUDED_IN_IMPORT), "UTF-8");
        } else {//from  www.java  2s  .  co  m
            linkString += "?" + ProtocolConstants.PARAM_EXCLUDE + "=" + URLEncoder
                    .encode(representation.getString(ProtocolConstants.KEY_EXCLUDED_IN_IMPORT), "UTF-8");
        }
        link = new URI(linkString);
        representation.remove(ProtocolConstants.KEY_EXCLUDED_IN_IMPORT);
    }
    representation.put(ProtocolConstants.KEY_IMPORT_LOCATION, link);
    //Bug 348073: don't add export links for empty directories
    if (isEmptyDirectory(request, targetPath)) {
        return;
    }
    path = new Path("/xfer/export").append(targetPath).addFileExtension("zip"); //$NON-NLS-1$ //$NON-NLS-2$
    link = new URI(resource.getScheme(), resource.getAuthority(), path.toString(), null, null);
    if (representation.has(ProtocolConstants.KEY_EXCLUDED_IN_EXPORT)) {
        String linkString = link.toString();
        if (linkString.contains("?")) {
            linkString += "&" + ProtocolConstants.PARAM_EXCLUDE + "=" + URLEncoder
                    .encode(representation.getString(ProtocolConstants.KEY_EXCLUDED_IN_EXPORT), "UTF-8");
        } else {
            linkString += "?" + ProtocolConstants.PARAM_EXCLUDE + "=" + URLEncoder
                    .encode(representation.getString(ProtocolConstants.KEY_EXCLUDED_IN_EXPORT), "UTF-8");
        }
        link = new URI(linkString);
        representation.remove(ProtocolConstants.KEY_EXCLUDED_IN_EXPORT);
    }
    representation.put(ProtocolConstants.KEY_EXPORT_LOCATION, link);
}