List of usage examples for java.lang.reflect Array getLength
@HotSpotIntrinsicCandidate public static native int getLength(Object array) throws IllegalArgumentException;
From source file:com.espertech.esper.client.scopetest.EPAssertionUtil.java
private static boolean compareArrayAndCollSize(Object expected, Collection actual) { if (expected == null && (actual == null || actual.size() == 0)) { return true; }//from w w w . j a va 2 s.c om if (expected == null || actual == null) { if (expected == null) { ScopeTestHelper.assertNull("Expected is null but actual is not null", actual); } ScopeTestHelper.assertNull("Actual is null but expected is not null", expected); } else { int expectedLength = Array.getLength(expected); int actualLength = actual.size(); ScopeTestHelper.assertEquals("Mismatch in the number of expected and actual length", expectedLength, actualLength); } return false; }
From source file:com.espertech.esper.client.scopetest.EPAssertionUtil.java
private static boolean compareArraySize(String message, Object expected, Object actual) { if ((expected == null) && (actual == null || Array.getLength(actual) == 0)) { return true; }//from w ww . j ava 2 s .c o m if (expected == null || actual == null) { String prefix = message != null ? message + ", " : ""; if (expected == null) { ScopeTestHelper.assertNull(prefix + "Expected is null but actual is not null", actual); } ScopeTestHelper.assertNull(prefix + "Actual is null but expected is not null", expected); } else { int expectedLength = Array.getLength(expected); int actualLength = Array.getLength(actual); String prefix = message != null ? message + ", " : ""; ScopeTestHelper.assertEquals( prefix + "Mismatch in the number of expected and actual number of values asserted", expectedLength, actualLength); } return false; }
From source file:org.jvnet.hudson.test.JenkinsRule.java
/** * Asserts that two JavaBeans are equal as far as the given list of properties are concerned. * * <p>/* w ww . j a va 2 s. c om*/ * This method takes two objects that have properties (getXyz, isXyz, or just the public xyz field), * and makes sure that the property values for each given property are equals (by using {@link org.junit.Assert#assertThat(Object, org.hamcrest.Matcher)}) * * <p> * Property values can be null on both objects, and that is OK, but passing in a property that doesn't * exist will fail an assertion. * * <p> * This method is very convenient for comparing a large number of properties on two objects, * for example to verify that the configuration is identical after a config screen roundtrip. * * @param lhs * One of the two objects to be compared. * @param rhs * The other object to be compared * @param properties * ','-separated list of property names that are compared. * @since 1.297 */ public void assertEqualBeans(Object lhs, Object rhs, String properties) throws Exception { assertThat("LHS", lhs, notNullValue()); assertThat("RHS", rhs, notNullValue()); for (String p : properties.split(",")) { PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(lhs, p); Object lp, rp; if (pd == null) { // field? try { Field f = lhs.getClass().getField(p); lp = f.get(lhs); rp = f.get(rhs); } catch (NoSuchFieldException e) { assertThat("No such property " + p + " on " + lhs.getClass(), pd, notNullValue()); return; } } else { lp = PropertyUtils.getProperty(lhs, p); rp = PropertyUtils.getProperty(rhs, p); } if (lp != null && rp != null && lp.getClass().isArray() && rp.getClass().isArray()) { // deep array equality comparison int m = Array.getLength(lp); int n = Array.getLength(rp); assertThat("Array length is different for property " + p, n, is(m)); for (int i = 0; i < m; i++) assertThat(p + "[" + i + "] is different", Array.get(rp, i), is(Array.get(lp, i))); return; } assertThat("Property " + p + " is different", rp, is(lp)); } }
From source file:com.github.crab2died.ExcelUtils.java
private void generateSheet(Workbook workbook, List<?> data, List<String> header, String sheetName) { Sheet sheet;/* www.j a v a 2 s . co m*/ if (null != sheetName && !"".equals(sheetName)) { sheet = workbook.createSheet(sheetName); } else { sheet = workbook.createSheet(); } int rowIndex = 0; if (null != header && header.size() > 0) { // Row row = sheet.createRow(rowIndex++); for (int i = 0; i < header.size(); i++) { row.createCell(i, CellType.STRING).setCellValue(header.get(i)); } } for (Object object : data) { Row row = sheet.createRow(rowIndex++); if (object.getClass().isArray()) { for (int j = 0; j < Array.getLength(object); j++) { row.createCell(j, CellType.STRING).setCellValue(Array.get(object, j).toString()); } } else if (object instanceof Collection) { Collection<?> items = (Collection<?>) object; int j = 0; for (Object item : items) { row.createCell(j++, CellType.STRING).setCellValue(item.toString()); } } else { row.createCell(0, CellType.STRING).setCellValue(object.toString()); } } }
From source file:org.alfresco.repo.content.metadata.AbstractMappingMetadataExtracter.java
/** * Adds a value to the map, conserving null values. Values are converted to null if: * <ul>/*from ww w . j av a2 s . c o m*/ * <li>it is an empty string value after trimming</li> * <li>it is an empty collection</li> * <li>it is an empty array</li> * </ul> * String values are trimmed before being put into the map. * Otherwise, it is up to the extracter to ensure that the value is a <tt>Serializable</tt>. * It is not appropriate to implicitly convert values in order to make them <tt>Serializable</tt> * - the best conversion method will depend on the value's specific meaning. * * @param key the destination key * @param value the serializable value * @param destination the map to put values into * @return Returns <tt>true</tt> if set, otherwise <tt>false</tt> */ protected boolean putRawValue(String key, Serializable value, Map<String, Serializable> destination) { if (value == null) { // Just keep this } else if (value instanceof String) { String valueStr = ((String) value).trim(); if (valueStr.length() == 0) { value = null; } else { if (valueStr.indexOf("\u0000") != -1) { valueStr = valueStr.replaceAll("\u0000", ""); } // Keep the trimmed value value = valueStr; } } else if (value instanceof Collection) { Collection<?> valueCollection = (Collection<?>) value; if (valueCollection.isEmpty()) { value = null; } } else if (value.getClass().isArray()) { if (Array.getLength(value) == 0) { value = null; } } // It passed all the tests destination.put(key, value); return true; }
From source file:com.servoy.j2db.util.Utils.java
public final static boolean equalObjects(Object oldObj, Object obj, double equalsPrecision, boolean ignoreCase) { if (oldObj instanceof Wrapper) oldObj = ((Wrapper) oldObj).unwrap(); if (obj instanceof Wrapper) obj = ((Wrapper) obj).unwrap(); if (oldObj == obj) { return true; }/*from w w w. j ava 2 s. c o m*/ if (oldObj == null && obj != null) { return false; } if (oldObj != null && obj == null) { return false; } // Compare UUID with possible storage for UUID if (oldObj.getClass() == UUID.class) { if (obj.getClass() == byte[].class && ((byte[]) obj).length == 16) { // compare UUID and byte[] return oldObj.equals(new UUID((byte[]) obj)); } if (obj.getClass() == String.class && ((String) obj).length() == 36) { // compare UUID and String return oldObj.toString().equals(obj); } return oldObj.equals(obj); } if (obj.getClass() == UUID.class) { if (oldObj.getClass() == byte[].class && ((byte[]) oldObj).length == 16) { // compare UUID and byte[] return obj.equals(new UUID((byte[]) oldObj)); } if (oldObj.getClass() == String.class && ((String) oldObj).length() == 36) { // compare UUID and String return obj.toString().equals(oldObj); } return obj.equals(oldObj); } if (oldObj.getClass().isArray() && obj.getClass().isArray()) { int length = Array.getLength(obj); if (length == Array.getLength(oldObj)) { for (int i = 0; i < length; i++) { if (!equalObjects(Array.get(obj, i), Array.get(oldObj, i), equalsPrecision, ignoreCase)) return false; } return true; } return false; } //in case one side is String and other Number -> make both string if (oldObj instanceof Number && obj instanceof String) { try { obj = new Double((String) obj); } catch (Exception e) { oldObj = oldObj.toString(); } } else if (obj instanceof Number && oldObj instanceof String) { try { oldObj = new Double((String) oldObj); } catch (Exception e) { obj = obj.toString(); } } if (oldObj instanceof BigDecimal && !(obj instanceof BigDecimal)) { if (obj instanceof Long) { obj = BigDecimal.valueOf(((Long) obj).longValue()); } else if (obj instanceof Double) { obj = BigDecimal.valueOf(((Double) obj).doubleValue()); } } else if (obj instanceof BigDecimal && !(oldObj instanceof BigDecimal)) { if (oldObj instanceof Long) { oldObj = BigDecimal.valueOf(((Long) oldObj).longValue()); } else if (oldObj instanceof Double) { oldObj = BigDecimal.valueOf(((Double) oldObj).doubleValue()); } } // separate tests for BigDecimal and Long, the tests based on Double may give // incorrect results for Long values not fitting in a double mantissa. // note that 2.0 is not equal to 2.00 according to BigDecimal.equals() if (oldObj instanceof BigDecimal && obj instanceof BigDecimal) { return ((BigDecimal) oldObj).subtract((BigDecimal) obj).abs().doubleValue() < equalsPrecision; } if (oldObj instanceof Long && obj instanceof Long) { return oldObj.equals(obj); } // Always cast to double so we don't lose precision. if (oldObj instanceof Number && obj instanceof Number) { if (oldObj instanceof Float || oldObj instanceof Double || oldObj instanceof BigDecimal || obj instanceof Float || obj instanceof Double || obj instanceof BigDecimal) { double a = ((Number) oldObj).doubleValue(); double b = ((Number) obj).doubleValue(); return a == b || Math.abs(a - b) < equalsPrecision; } return ((Number) oldObj).longValue() == ((Number) obj).longValue(); } if (oldObj instanceof Date && obj instanceof Date) { return (((Date) oldObj).getTime() == ((Date) obj).getTime()); } if (ignoreCase && oldObj instanceof String && obj instanceof String) { return ((String) oldObj).equalsIgnoreCase((String) obj); } return oldObj.equals(obj); }
From source file:edu.stanford.muse.util.Util.java
/** * converts an object to a string->string map by converting all its fields * (fields may be non-public//from w w w .j a v a 2s . com * if running without security manager). expand=true expands collections * (array, list, map) */ public static Map<String, String> convertObjectToMap(Object o, boolean expand) { Map<String, String> map = new LinkedHashMap<String, String>(); if (o == null) return map; Class c = o.getClass(); try { // generate a string to string map of the fields Field f[] = c.getDeclaredFields(); for (int i = 0; i < f.length; i++) { boolean acc = f[i].isAccessible(); if (!acc) f[i].setAccessible(true); // ok to do in absence of a security manager Class t = f[i].getType(); String name = f[i].getName(); if (name.indexOf("$") >= 0) // outer class, skip" + continue; if (t == double.class) map.put(name, Double.toString(f[i].getDouble(o))); else if (t == float.class) map.put(name, Float.toString(f[i].getFloat(o))); else if (t == int.class) map.put(name, Integer.toString(f[i].getInt(o))); else if (t == long.class) map.put(name, Long.toString(f[i].getLong(o))); else if (t == char.class) map.put(name, f[i].getChar(o) + "(" + Integer.toString(f[i].getChar(o)) + ")"); else if (t == short.class) map.put(name, Short.toString(f[i].getShort(o))); else if (t == byte.class) map.put(name, Byte.toString(f[i].getByte(o))); else if (t == boolean.class) map.put(name, Boolean.toString(f[i].getBoolean(o))); else { // field is of object type Object val = f[i].get(o); // o.f[i]'s type is t, value is // val if (val == null) map.put(name, "null"); else { Class valClass = val.getClass(); if (valClass.isArray()) { if (expand) for (int x = 0; x < Array.getLength(val); x++) map.put(name + "[" + x + "]", Array.get(val, x) + ""); } else if (java.util.Map.class.isAssignableFrom(valClass)) // could // also // check // t, // but // val.getClass // is // more // specific { Map m = (Map) f[i].get(o); if (expand) for (Object x : m.keySet()) map.put(name + "." + x, m.get(x) + ""); } // could also check t, but val.getClass is more specific else if (java.util.Collection.class.isAssignableFrom(valClass)) { Collection c1 = (Collection) f[i].get(o); if (expand) { int count = 0; for (Object o1 : c1) map.put(name + "(" + count++ + ")", o1 + ""); // use // () // instead // of // [] // to // distinguish // from // arrays } } else map.put(name, "[" + val.toString() + "]"); } } if (!acc) f[i].setAccessible(false); } } catch (Throwable e) { Util.print_exception(e); } return map; }
From source file:edu.brown.utils.PartitionEstimator.java
/** * Calculate the partitions touched for the given column * //from ww w. j a va2s . c om * @param partitions * @param params * @param predicates * @param catalog_col */ private void calculatePartitions(final PartitionSet partitions, final Object params[], final boolean is_array[], final List<Pair<ExpressionType, CatalogType>> predicates, final Column catalog_col) throws Exception { // Note that we have to go through all of the mappings from the partitioning column // to parameters. This can occur when the partitioning column is referenced multiple times // This allows us to handle complex WHERE clauses and what not. for (Pair<ExpressionType, CatalogType> pair : predicates) { ExpressionType expType = pair.getFirst(); CatalogType param = pair.getSecond(); // HACK HACK HACK // If this is not an equality comparison, then it has to go to all partitions. // If we ever want to support smarter range partitioning, then // we will need to move the logic that examines the expression type into // the hasher code. if (expType != ExpressionType.COMPARE_EQUAL) { partitions.addAll(this.all_partitions); break; } // STATEMENT PARAMETER // This is the common case if (param instanceof StmtParameter) { int param_idx = ((StmtParameter) param).getIndex(); // IMPORTANT: Check if the parameter is an array. If it is, then we // have to loop through and get the hash of all of the values if (is_array[param_idx]) { int num_elements = Array.getLength(params[param_idx]); if (trace.val) LOG.trace(String.format("%s is an array. Calculating multiple partitions", param)); for (int i = 0; i < num_elements; i++) { Object value = Array.get(params[param_idx], i); int partition_id = this.hasher.hash(value, catalog_col); if (trace.val) LOG.trace(String.format("%s HASHING PARAM ARRAY[%d][%d]: %s -> %d", catalog_col.fullName(), param_idx, i, value, partition_id)); partitions.add(partition_id); } // FOR } // Primitive Value else { int partition_id = this.hasher.hash(params[param_idx], catalog_col); if (trace.val) LOG.trace(String.format("%s HASHING PARAM [%d]: %s -> %d", catalog_col.fullName(), param_idx, params[param_idx], partition_id)); partitions.add(partition_id); } } // CONSTANT VALUE // This is more rare else if (param instanceof ConstantValue) { ConstantValue const_param = (ConstantValue) param; VoltType vtype = VoltType.get(const_param.getType()); Object const_value = VoltTypeUtil.getObjectFromString(vtype, const_param.getValue()); int partition_id = this.hasher.hash(const_value); partitions.add(partition_id); } // BUSTED! else { throw new RuntimeException("Unexpected parameter type: " + param.fullName()); } } // FOR return; }
From source file:edu.brown.utils.PartitionEstimator.java
/** * Return the partition touched for a given procedure's parameter value. * If the given parameter is an array, then we will just use the first element. * @param catalog_proc//from w ww . j a va 2s .c om * @param partition_param_val * @param is_array Whether the value is an array. * @return * @throws Exception */ private int calculatePartition(final Procedure catalog_proc, Object param_val, final boolean is_array) throws Exception { // If the parameter is an array, then just use the first value if (is_array) { int num_elements = Array.getLength(param_val); if (num_elements == 0) { if (debug.val) LOG.warn("Empty partitioning parameter array for " + catalog_proc); return (HStoreConstants.NULL_PARTITION_ID); } else { param_val = Array.get(param_val, 0); } } else if (param_val == null) { if (debug.val) LOG.warn("Null ProcParameter value: " + catalog_proc); return (HStoreConstants.NULL_PARTITION_ID); } return (this.hasher.hash(param_val, catalog_proc)); }
From source file:jef.tools.XMLUtils.java
private static Element appendBean(Node parent, Object bean, Class<?> type, Boolean asAttrib, String tagName) { if (type == null) { if (bean == null) { return null; }/*from w ww . j a va 2 s.c o m*/ type = bean.getClass(); } if (tagName == null || tagName.length() == 0) { tagName = type.getSimpleName(); } if (type.isArray()) { if (bean == null) return null; Element collection = addElement(parent, tagName); for (int i = 0; i < Array.getLength(bean); i++) { appendBean(collection, Array.get(bean, i), null, asAttrib, null); } return collection; } else if (Collection.class.isAssignableFrom(type)) { if (bean == null) return null; Element collection = addElement(parent, tagName); for (Object obj : (Collection<?>) bean) { appendBean(collection, obj, null, asAttrib, null); } return collection; } else if (Map.class.isAssignableFrom(type)) { Element map = addElement(parent, tagName); for (Entry<?, ?> e : ((Map<?, ?>) bean).entrySet()) { Element entry = XMLUtils.addElement(map, "entry"); Element key = XMLUtils.addElement(entry, "key"); appendBean(key, e.getKey(), null, asAttrib, null); Element value = XMLUtils.addElement(entry, "value"); appendBean(value, e.getValue(), null, asAttrib, null); } return map; } else if (CharSequence.class.isAssignableFrom(type)) { if (Boolean.TRUE.equals(asAttrib)) { ((Element) parent).setAttribute(tagName, StringUtils.toString(bean)); } else { addElement(parent, tagName, StringUtils.toString(bean)); } } else if (Date.class.isAssignableFrom(type)) { if (Boolean.FALSE.equals(asAttrib)) { addElement(parent, tagName, DateUtils.formatDateTime((Date) bean)); } else { ((Element) parent).setAttribute(tagName, DateUtils.formatDateTime((Date) bean)); } } else if (Number.class.isAssignableFrom(type) || type.isPrimitive() || type == Boolean.class) { if (Boolean.FALSE.equals(asAttrib)) { addElement(parent, tagName, StringUtils.toString(bean)); } else { ((Element) parent).setAttribute(tagName, StringUtils.toString(bean)); } } else { if (bean == null) return null; Element root = addElement(parent, type.getSimpleName()); BeanWrapper bw = BeanWrapper.wrap(bean); for (Property p : bw.getProperties()) { appendBean(root, p.get(bean), p.getType(), asAttrib, p.getName()); } return root; } return null; }