List of usage examples for java.lang Object equals
public boolean equals(Object obj)
From source file:de.cgarbs.lib.json.JSONDataModel.java
/** * Copies the JSON data to the DataModel's attributs. * @param model the DataModel to write to * @param json the parsed JSON data to read * @throws JSONException when there is an error during the JSON conversion * @throws DataException when there is an error setting a value in die DataModel *//*from w ww . ja v a2 s . c o m*/ static void readFromJSON(final DataModel model, final Object json) throws JSONException, DataException { if (!(json instanceof Map)) { throw newJSONToJavaError("root element is no map"); } final Map<String, Object> jsonMap = (Map<String, Object>) json; final Object identifier = jsonMap.get(IDENTIFIER_FIELD); final Object version = jsonMap.get(VERSION_FIELD); final Object attributes = jsonMap.get(ATTRIBUTE_FIELD); // check null if (identifier == null) { throw newJSONToJavaError("identifier [" + IDENTIFIER_FIELD + "] is missing"); } if (version == null) { throw newJSONToJavaError("version [" + VERSION_FIELD + "] is missing"); } if (attributes == null) { throw newJSONToJavaError("attributes [" + ATTRIBUTE_FIELD + "] are missing"); } // check values if (!IDENTIFIER.equals(identifier)) { throw newJSONToJavaError("wrong identifier [" + IDENTIFIER_FIELD + "]: expected <" + IDENTIFIER + ">, but got <" + identifier.toString() + ">"); } if (!VERSION.equals(version)) { throw newJSONToJavaError("wrong version [" + VERSION_FIELD + "]: expected <" + VERSION + ">, but got <" + version.toString() + ">"); } if (!(attributes instanceof Map)) { throw newJSONToJavaError("wrong attributes [" + ATTRIBUTE_FIELD + "]: expected a <Map> but got a <" + attributes.getClass().toString() + ">"); } final Map<String, Object> attributeMap = (Map<String, Object>) attributes; final Set<String> validAttributes = model.getAttributeKeys(); for (final String key : attributeMap.keySet()) { if (validAttributes.contains(key)) { model.setValue(key, JSONAdapter.prepareForJava(attributeMap.get(key))); } } }
From source file:com.icesoft.faces.renderkit.dom_html_basic.DomBasicRenderer.java
/** * <p/>/* ww w . j a va2 s . c om*/ * Sets a non-null, non-empty-string, UIComponent property to the * corresponding DOM Element * <p/> * * @param uiComponent the source of the attribute value * @param targetElement the DOM Element that will receive the * attribute * @param attrNameInComponent the property name in the UIComponent object * @param attrNameInDom the attribute name in the DOM Element */ public static void renderAttribute(UIComponent uiComponent, Element targetElement, String attrNameInComponent, String attrNameInDom) { Object attrValue = uiComponent.getAttributes().get(attrNameInComponent); if (attrValue != null && !attrValue.equals("")) { if (attrValue.toString().equalsIgnoreCase("true") || attrValue.toString().equalsIgnoreCase("false")) { boolean trueValue = new Boolean(attrValue.toString()).booleanValue(); if (!trueValue) { targetElement.removeAttribute(attrNameInDom.toString()); return; } } targetElement.setAttribute(attrNameInDom.toString(), attrValue.toString()); } }
From source file:com.autobizlogic.abl.util.BeanUtil.java
/** * Given two beans of the same entity, determine whether they are equal. This is done by * looking at the value of all the attributes, and the value of all the parent * relationships. If there is any difference, false is returned. */// ww w .j av a 2s. com @SuppressWarnings("rawtypes") public static boolean beansAreEqual(MetaEntity metaEntity, Object bean1, Object bean2) { // First the easy cases if (bean1 == null && bean2 == null) return true; if (bean1 == null && bean2 != null) return false; if (bean1 != null && bean2 == null) return false; if (bean1 == bean2) // You never know... return true; Map beanMap1 = null; Map beanMap2 = null; if (metaEntity.isMap()) { beanMap1 = (Map) bean1; beanMap2 = (Map) bean2; } else { beanMap1 = new BeanMap(bean1); beanMap2 = new BeanMap(bean2); } // Compare the attributes - return at first difference Set<MetaAttribute> metaAttributes = metaEntity.getMetaAttributes(); for (MetaAttribute metaAttribute : metaAttributes) { Object val1 = beanMap1.get(metaAttribute.getName()); Object val2 = beanMap2.get(metaAttribute.getName()); if (val1 == null && val2 == null) continue; if (val1 != null && val2 != null && val1 == val2) continue; if (val1 != null && val2 != null && val1.equals(val2)) continue; return false; } Set<MetaRole> metaRoles = metaEntity.getRolesFromChildToParents(); for (MetaRole metaRole : metaRoles) { Object val1 = beanMap1.get(metaRole.getRoleName()); Object val2 = beanMap2.get(metaRole.getRoleName()); if (val1 == null && val2 == null) continue; if (val1 != null && val2 != null && val1 == val2) continue; if (val1 != null && val2 != null && val1.equals(val2)) continue; return false; } return true; }
From source file:Debug.java
public static boolean compare(String prefix, Map a, Map b, ArrayList ignore, StringBuffer buffer) { if ((a == null) && (b == null)) { log(buffer, prefix + " both maps null"); return true; }/* w w w . ja va 2s. c om*/ if (a == null) { log(buffer, prefix + " map a: null, map b: map"); return false; } if (b == null) { log(buffer, prefix + " map a: map, map b: null"); return false; } ArrayList keys_a = new ArrayList(a.keySet()); ArrayList keys_b = new ArrayList(b.keySet()); if (ignore != null) { keys_a.removeAll(ignore); keys_b.removeAll(ignore); } boolean result = true; for (int i = 0; i < keys_a.size(); i++) { Object key = keys_a.get(i); if (!keys_b.contains(key)) { log(buffer, prefix + "b is missing key '" + key + "' from a"); result = false; } else { keys_b.remove(key); Object value_a = a.get(key); Object value_b = b.get(key); if (!value_a.equals(value_b)) { log(buffer, prefix + "key(" + key + ") value a: " + value_a + ") != b: " + value_b + ")"); result = false; } } } for (int i = 0; i < keys_b.size(); i++) { Object key = keys_b.get(i); log(buffer, prefix + "a is missing key '" + key + "' from b"); result = false; } if (result) log(buffer, prefix + "a is the same as b"); return result; }
From source file:com.phoenixst.plexus.GraphUtils.java
/** * Tests two objects for being <code>.equals()</code>, handling * <code>null</code> appropriately. */// ww w . j a v a 2s.c om public static final boolean equals(Object a, Object b) { return (a == null) ? (b == null) : a.equals(b); }
From source file:com.flexive.faces.FxJsfComponentUtils.java
/** * Check if an item is selected//from w w w .j av a 2s . c o m * * @param context faces context * @param component our component * @param itemValue the value to check for selection * @param valueArray all values to compare against * @param converter the converter * @return selected */ public static boolean isSelectItemSelected(FacesContext context, UIComponent component, Object itemValue, Object valueArray, Converter converter) { if (itemValue == null && valueArray == null) return true; if (null != valueArray) { if (!valueArray.getClass().isArray()) { LOG.warn("valueArray is not an array, the actual type is " + valueArray.getClass()); return valueArray.equals(itemValue); } int len = Array.getLength(valueArray); for (int i = 0; i < len; i++) { Object value = Array.get(valueArray, i); if (value == null && itemValue == null) { return true; } else { if ((value == null) ^ (itemValue == null)) continue; Object compareValue; if (converter == null) { compareValue = coerceToModelType(context, itemValue, value.getClass()); } else { compareValue = itemValue; if (compareValue instanceof String && !(value instanceof String)) { // type mismatch between the time and the value we're // comparing. Invoke the Converter. compareValue = converter.getAsObject(context, component, (String) compareValue); } } if (value.equals(compareValue)) return true; //selected } } } return false; }
From source file:de.pribluda.android.jsonmarshaller.JSONUnmarshaller.java
/** * TODO: provide support for nested JSON objects * TODO: provide support for embedded JSON Arrays * * @param jsonObject// ww w .j ava2 s .c o m * @param beanToBeCreatedClass * @param <T> * @return * @throws IllegalAccessException * @throws InstantiationException * @throws JSONException * @throws NoSuchMethodException * @throws java.lang.reflect.InvocationTargetException */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T> T unmarshall(JSONObject jsonObject, Class<T> beanToBeCreatedClass) throws IllegalAccessException, InstantiationException, JSONException, NoSuchMethodException, InvocationTargetException { T value = beanToBeCreatedClass.getConstructor().newInstance(); Iterator keys = jsonObject.keys(); while (keys.hasNext()) { String key = (String) keys.next(); Object field = jsonObject.get(key); // capitalise to standard setter pattern String methodName = SETTER_PREFIX + key.substring(0, 1).toUpperCase() + key.substring(1); //System.err.println("method name:" + methodName); Method method = getCandidateMethod(beanToBeCreatedClass, methodName); if (method != null) { Class clazz = method.getParameterTypes()[0]; // discriminate based on type if (field.equals(JSONObject.NULL)) { method.invoke(value, clazz.cast(null)); } else if (field instanceof String) { // check if we're an enum if (clazz.isEnum()) { Object enm = clazz.getMethod("valueOf", String.class).invoke(null, field); try { beanToBeCreatedClass.getMethod(methodName, clazz).invoke(value, enm); continue; } catch (NoSuchMethodException e) { // that means there was no such method, proceed } } // string shall be used directly, either to set or as constructor parameter (if suitable) try { beanToBeCreatedClass.getMethod(methodName, String.class).invoke(value, field); continue; } catch (NoSuchMethodException e) { // that means there was no such method, proceed } // or maybe there is method with suitable parameter? if (clazz.isPrimitive() && primitves.get(clazz) != null) { clazz = primitves.get(clazz); } try { method.invoke(value, clazz.getConstructor(String.class).newInstance(field)); } catch (NoSuchMethodException nsme) { // we are failed here, but so what? be lenient } } // we are done with string else if (clazz.isArray() || clazz.isAssignableFrom(List.class)) { // JSON array corresponds either to array type, or to some collection if (field instanceof JSONObject) { JSONArray array = new JSONArray(); array.put(field); field = array; } // we are interested in arrays for now if (clazz.isArray()) { // populate field value from JSON Array Object fieldValue = populateRecursive(clazz, field); method.invoke(value, fieldValue); } else if (clazz.isAssignableFrom(List.class)) { try { Type type = method.getGenericParameterTypes()[0]; if (type instanceof ParameterizedType) { Type param = ((ParameterizedType) type).getActualTypeArguments()[0]; if (param instanceof Class) { Class c = (Class) param; // populate field value from JSON Array Object fieldValue = populateRecursiveList(clazz, c, field); method.invoke(value, fieldValue); } } } catch (Exception e) { // failed } } } else if (field instanceof JSONObject) { // JSON object means nested bean - process recursively method.invoke(value, unmarshall((JSONObject) field, clazz)); } else if (clazz.equals(Date.class)) { method.invoke(value, new Date((Long) field)); } else { // fallback here, types not yet processed will be // set directly ( if possible ) // TODO: guard this? for better leniency method.invoke(value, field); } } } return value; }
From source file:com.mongodb.hadoop.util.MongoSplitter.java
/** * This constructs splits using the chunk boundaries. *///from w w w. j ava 2 s. co m private static List<InputSplit> fetchSplitsViaChunks(final MongoConfig conf, MongoURI uri, Mongo mongo, boolean useShards, Boolean slaveOk) { DBObject originalQuery = conf.getQuery(); if (useShards) log.warn("WARNING getting splits that connect directly to the backend mongods" + " is risky and might not produce correct results"); if (conf.isRangeQueryEnabled()) { log.warn("WARNING using range queries can produce incorrect results if values" + " stored under the splitting key have different types."); } if (log.isDebugEnabled()) { log.debug("getSplitsUsingChunks(): originalQuery: " + originalQuery); } DB configDB = mongo.getDB("config"); Map<String, String> shardMap = null; //key: shardname, value: host if (useShards) { shardMap = new HashMap<String, String>(); DBCollection shardsCollection = configDB.getCollection("shards"); DBCursor cur = shardsCollection.find(); try { while (cur.hasNext()) { final BasicDBObject row = (BasicDBObject) cur.next(); String host = row.getString("host"); // for replica sets host will look like: "setname/localhost:20003,localhost:20004" int slashIndex = host.indexOf('/'); if (slashIndex > 0) host = host.substring(slashIndex + 1); shardMap.put((String) row.get("_id"), host); } } finally { if (cur != null) cur.close(); } } if (log.isDebugEnabled()) { log.debug("MongoInputFormat.getSplitsUsingChunks(): shard map is: " + shardMap); } DBCollection chunksCollection = configDB.getCollection("chunks"); /* Chunks looks like: { "_id" : "test.lines-_id_ObjectId('4d60b839874a8ad69ad8adf6')", "lastmod" : { "t" : 3000, "i" : 1 }, "ns" : "test.lines", "min" : { "_id" : ObjectId("4d60b839874a8ad69ad8adf6") }, "max" : { "_id" : ObjectId("4d60b83a874a8ad69ad8d1a9") }, "shard" : "shard0000" } { "_id" : "test.lines-_id_ObjectId('4d60b848874a8ad69ada8756')", "lastmod" : { "t" : 3000, "i" : 19 }, "ns" : "test.lines", "min" : { "_id" : ObjectId("4d60b848874a8ad69ada8756") }, "max" : { "_id" : { $maxKey : 1 } }, "shard" : "shard0002" } */ BasicDBObject query = new BasicDBObject(); query.put("ns", uri.getDatabase() + "." + uri.getCollection()); DBCursor cur = chunksCollection.find(query); try { int numChunks = 0; final int numExpectedChunks = cur.size(); final List<InputSplit> splits = new ArrayList<InputSplit>(numExpectedChunks); while (cur.hasNext()) { numChunks++; final BasicDBObject row = (BasicDBObject) cur.next(); DBObject minObj = ((DBObject) row.get("min")); DBObject shardKeyQuery = new BasicDBObject(); BasicDBObject min = new BasicDBObject(); BasicDBObject max = new BasicDBObject(); for (String keyName : minObj.keySet()) { Object tMin = minObj.get(keyName); Object tMax = ((DBObject) row.get("max")).get(keyName); /** The shard key can be of any possible type, so this must be kept as Object */ if (!(tMin == SplitFriendlyDBCallback.MIN_KEY_TYPE || tMin.equals("MinKey"))) min.put(keyName, tMin); if (!(tMax == SplitFriendlyDBCallback.MAX_KEY_TYPE || tMax.equals("MaxKey"))) max.put(keyName, tMax); } /** We have to put something for $query or we'll fail; if no original query use an empty DBObj */ if (originalQuery == null) originalQuery = new BasicDBObject(); DBObject splitQuery = originalQuery; boolean useMinMax = true; if (conf.isRangeQueryEnabled()) { Map.Entry<String, Object> minKey = min.size() == 1 ? min.entrySet().iterator().next() : null; Map.Entry<String, Object> maxKey = max.size() == 1 ? max.entrySet().iterator().next() : null; if (minKey == null && maxKey == null) { throw new IllegalArgumentException( "Range query is enabled but one or more split boundaries contains a compound key:\n" + "minKey: " + min.toString() + "\n" + "maxKey: " + max.toString()); } if ((minKey != null && originalQuery.containsKey(minKey.getKey())) || (maxKey != null && originalQuery.containsKey(maxKey.getKey()))) { throw new IllegalArgumentException( "Range query is enabled but split key conflicts with query filter:\n" + "minKey: " + min.toString() + "\n" + "maxKey: " + max.toString() + "\n" + "query: " + originalQuery.toString()); } BasicDBObject rangeObj = new BasicDBObject(); if (minKey != null)//&& !SplitFriendlyDBCallback.MIN_KEY_TYPE.equals(minKey.getValue())){ rangeObj.put("$gte", minKey.getValue()); //} if (maxKey != null)//&& !SplitFriendlyDBCallback.MAX_KEY_TYPE.equals(maxKey.getValue())){ rangeObj.put("$lt", maxKey.getValue()); //} splitQuery = new BasicDBObject(); splitQuery.putAll(originalQuery); splitQuery.put(minKey.getKey(), rangeObj); useMinMax = false; } shardKeyQuery.put("$query", originalQuery); if (log.isDebugEnabled()) { log.debug("[" + numChunks + "/" + numExpectedChunks + "] new query is: " + shardKeyQuery); } MongoURI inputURI = conf.getInputURI(); if (useShards) { final String shardname = row.getString("shard"); String host = shardMap.get(shardname); inputURI = getNewURI(inputURI, host, slaveOk); } if (useMinMax) { MongoInputSplit split = new MongoInputSplit(inputURI, conf.getInputKey(), splitQuery, conf.getFields(), conf.getSort(), // TODO - should inputKey be the shard key? min, max, conf.getLimit(), conf.getSkip(), conf.isNoTimeout()); splits.add(split); } else { MongoInputSplit split = new MongoInputSplit(inputURI, conf.getInputKey(), splitQuery, conf.getFields(), conf.getSort(), // TODO - should inputKey be the shard key? null, null, conf.getLimit(), conf.getSkip(), conf.isNoTimeout()); splits.add(split); } } if (log.isDebugEnabled()) { log.debug("MongoInputFormat.getSplitsUsingChunks(): There were " + numChunks + " chunks, returning " + splits.size() + " splits: " + splits); } return splits; } finally { if (cur != null) cur.close(); } }
From source file:com.algoTrader.vo.BarVO.java
/** * This is a convenient helper method which is able to detect whether or not two values are equal. Two values * are equal when they are both {@code null}, are arrays of the same length with equal elements or are * equal objects (this includes {@link java.util.Collection} and {@link java.util.Map} instances). * * <p/>Note that for array, collection or map instances the comparison runs one level deep. * * @param first the first object to compare, may be {@code null} * @param second the second object to compare, may be {@code null} * @return this method will return {@code true} in case both objects are equal as explained above; * in all other cases this method will return {@code false} *///from w w w .j av a2s .c om protected static boolean equal(final Object first, final Object second) { final boolean equal; if (first == null) { equal = (second == null); } else if (first.getClass().isArray() && (second != null) && second.getClass().isArray()) { equal = Arrays.equals((Object[]) first, (Object[]) second); } else // note that the following also covers java.util.Collection and java.util.Map { equal = first.equals(second); } return equal; }
From source file:com.facebook.GraphObjectWrapper.java
/** * Determines if two GraphObjects represent the same underlying graph object, based on their IDs. * @param a a graph object//from w ww .j av a2s . c o m * @param b another graph object * @return true if both graph objects have an ID and it is the same ID, false otherwise */ public static boolean hasSameId(GraphObject a, GraphObject b) { if (a == null || b == null || !a.asMap().containsKey("id") || !b.asMap().containsKey("id")) { return false; } if (a.equals(b)) { return true; } Object idA = a.getProperty("id"); Object idB = b.getProperty("id"); if (idA == null || idB == null || !(idA instanceof String) || !(idB instanceof String)) { return false; } return idA.equals(idB); }