List of usage examples for java.lang.reflect Array get
public static native Object get(Object array, int index) throws IllegalArgumentException, ArrayIndexOutOfBoundsException;
From source file:org.apache.myfaces.config.ManagedBeanBuilder.java
@SuppressWarnings("unchecked") private void initializeProperties(FacesContext facesContext, ManagedBean beanConfiguration, Object bean) { ELResolver elResolver = facesContext.getApplication().getELResolver(); ELContext elContext = facesContext.getELContext(); for (ManagedProperty property : beanConfiguration.getManagedProperties()) { Object value = null;/*from w w w .j a va 2s .c o m*/ switch (property.getType()) { case ManagedProperty.TYPE_LIST: // JSF 1.1, 5.3.1.3 // Call the property getter, if it exists. // If the getter returns null or doesn't exist, create a java.util.ArrayList, // otherwise use the returned Object ... if (PropertyUtils.isReadable(bean, property.getPropertyName())) { value = elResolver.getValue(elContext, bean, property.getPropertyName()); } value = value == null ? new ArrayList<Object>() : value; if (value instanceof List) { initializeList(facesContext, property.getListEntries(), (List<Object>) value); } else if (value != null && value.getClass().isArray()) { int length = Array.getLength(value); ArrayList<Object> temp = new ArrayList<Object>(length); for (int i = 0; i < length; i++) { temp.add(Array.get(value, i)); } initializeList(facesContext, property.getListEntries(), temp); value = Array.newInstance(value.getClass().getComponentType(), temp.size()); length = temp.size(); for (int i = 0; i < length; i++) { Array.set(value, i, temp.get(i)); } } else { value = new ArrayList<Object>(); initializeList(facesContext, property.getListEntries(), (List<Object>) value); } break; case ManagedProperty.TYPE_MAP: // JSF 1.1, 5.3.1.3 // Call the property getter, if it exists. // If the getter returns null or doesn't exist, create a java.util.HashMap, // otherwise use the returned java.util.Map . if (PropertyUtils.isReadable(bean, property.getPropertyName())) { value = elResolver.getValue(elContext, bean, property.getPropertyName()); } value = value == null ? new HashMap<Object, Object>() : value; if (!(value instanceof Map)) { value = new HashMap<Object, Object>(); } initializeMap(facesContext, property.getMapEntries(), (Map<Object, Object>) value); break; case ManagedProperty.TYPE_NULL: break; case ManagedProperty.TYPE_VALUE: // check for correct scope of a referenced bean if (!isInValidScope(facesContext, property, beanConfiguration)) { throw new FacesException("Property " + property.getPropertyName() + " references object in a scope with shorter lifetime than the target scope " + beanConfiguration.getManagedBeanScope()); } value = property.getRuntimeValue(facesContext); break; default: throw new FacesException("unknown ManagedProperty type: " + property.getType()); } Class<?> propertyClass = null; if (property.getPropertyClass() == null) { propertyClass = elResolver.getType(elContext, bean, property.getPropertyName()); } else { propertyClass = ClassUtils.simpleJavaTypeToClass(property.getPropertyClass()); } if (null == propertyClass) { throw new IllegalArgumentException( "unable to find the type of property " + property.getPropertyName()); } Object coercedValue = coerceToType(facesContext, value, propertyClass); elResolver.setValue(elContext, bean, property.getPropertyName(), coercedValue); } }
From source file:org.kmnet.com.fw.web.message.MessagesPanelTag.java
/** * Writes the messages which have been set in the model * <p>/*from w w w .ja va 2 s . com*/ * If messages stored in the model is in the form of a class that extends * {@code Iterable} or an Array, {@link #writeMessage(TagWriter, Object)} is * called multiple times, to write<br> * {@link #innerElement} and messages.<br> * * If there is only a single message, this method calls * {@link #writeMessage(TagWriter, Object)} only once * </p> * * @param tagWriter * @param messages * @throws JspException * If {@link JspException} occurs in caller writeMessage */ protected void writeMessages(TagWriter tagWriter, Object messages) throws JspException { Class<?> clazz = messages.getClass(); if (Iterable.class.isAssignableFrom(clazz)) { Iterable<?> col = (Iterable<?>) messages; for (Object message : col) { writeMessage(tagWriter, message); } } else if (clazz.isArray()) { Class<?> type = clazz.getComponentType(); if (Object.class.isAssignableFrom(type)) { Object[] arr = (Object[]) messages; for (Object message : arr) { writeMessage(tagWriter, message); } } else { int len = Array.getLength(messages); for (int i = 0; i < len; i++) { Object message = Array.get(messages, i); writeMessage(tagWriter, message); } } } else { writeMessage(tagWriter, messages); } }
From source file:org.apache.myfaces.ov2021.config.ManagedBeanBuilder.java
@SuppressWarnings("unchecked") private void initializeProperties(FacesContext facesContext, ManagedBean beanConfiguration, Object bean) { ELResolver elResolver = facesContext.getApplication().getELResolver(); ELContext elContext = facesContext.getELContext(); for (ManagedProperty property : beanConfiguration.getManagedProperties()) { Object value = null;//from ww w. j av a 2 s . c o m switch (property.getType()) { case ManagedProperty.TYPE_LIST: // JSF 1.1, 5.3.1.3 // Call the property getter, if it exists. // If the getter returns null or doesn't exist, create a java.util.ArrayList, // otherwise use the returned Object ... if (PropertyUtils.isReadable(bean, property.getPropertyName())) { value = elResolver.getValue(elContext, bean, property.getPropertyName()); } value = value == null ? new ArrayList<Object>() : value; if (value instanceof List) { initializeList(facesContext, property.getListEntries(), (List<Object>) value); } else if (value != null && value.getClass().isArray()) { int length = Array.getLength(value); ArrayList<Object> temp = new ArrayList<Object>(length); for (int i = 0; i < length; i++) { temp.add(Array.get(value, i)); } initializeList(facesContext, property.getListEntries(), temp); value = Array.newInstance(value.getClass().getComponentType(), temp.size()); length = temp.size(); for (int i = 0; i < length; i++) { Array.set(value, i, temp.get(i)); } } else { value = new ArrayList<Object>(); initializeList(facesContext, property.getListEntries(), (List<Object>) value); } break; case ManagedProperty.TYPE_MAP: // JSF 1.1, 5.3.1.3 // Call the property getter, if it exists. // If the getter returns null or doesn't exist, create a java.util.HashMap, // otherwise use the returned java.util.Map . if (PropertyUtils.isReadable(bean, property.getPropertyName())) value = elResolver.getValue(elContext, bean, property.getPropertyName()); value = value == null ? new HashMap<Object, Object>() : value; if (!(value instanceof Map)) { value = new HashMap<Object, Object>(); } initializeMap(facesContext, property.getMapEntries(), (Map<Object, Object>) value); break; case ManagedProperty.TYPE_NULL: break; case ManagedProperty.TYPE_VALUE: // check for correct scope of a referenced bean if (!isInValidScope(facesContext, property, beanConfiguration)) { throw new FacesException("Property " + property.getPropertyName() + " references object in a scope with shorter lifetime than the target scope " + beanConfiguration.getManagedBeanScope()); } value = property.getRuntimeValue(facesContext); break; } Class<?> propertyClass = null; if (property.getPropertyClass() == null) { propertyClass = elResolver.getType(elContext, bean, property.getPropertyName()); } else { propertyClass = ClassUtils.simpleJavaTypeToClass(property.getPropertyClass()); } if (null == propertyClass) { throw new IllegalArgumentException( "unable to find the type of property " + property.getPropertyName()); } Object coercedValue = coerceToType(facesContext, value, propertyClass); elResolver.setValue(elContext, bean, property.getPropertyName(), coercedValue); } }
From source file:edu.cmu.cs.lti.util.general.BasicConvenience.java
/** * Given 2 arrays which may be arrays of other things, * determine if they have exactly the same dimensions, to some level * @param a1// w ww . j a v a 2 s .c o m * @param a2 * @param levels 1 means an array X[], 2 means X[] [], etc. * @return true if all dimensions are the same */ public static boolean allArrayDimensionsEqual(Object a1, Object a2, int levels) { int length = Array.getLength(a1); if (length != Array.getLength(a2)) { return false; } if (levels > 1) { for (int i = 0; i < length; i++) { if (!allArrayDimensionsEqual(Array.get(a1, i), Array.get(a2, i), levels - 1)) { return false; } } } return true; }
From source file:com.twosigma.beaker.sql.QueryExecutor.java
private QueryResult executeQuery(int currentIterationIndex, BeakerParseResult queryLine, Connection conn, NamespaceClient namespaceClient) throws SQLException, ReadVariableException { QueryResult queryResult = new QueryResult(); try (PreparedStatement statement = conn.prepareStatement(queryLine.getResultQuery())) { this.statement = statement; int n = 1; for (BeakerInputVar parameter : queryLine.getInputVars()) { if (parameter.getErrorMessage() != null) throw new ReadVariableException(parameter.getErrorMessage()); Object obj;/* w w w . j a v a 2 s. c o m*/ try { obj = namespaceClient.get(parameter.objectName); if (!parameter.isArray() && !parameter.isObject()) { statement.setObject(n, obj); } else if (!parameter.isArray() && parameter.isObject()) { statement.setObject(n, getValue(obj, parameter.getFieldName())); } else if (parameter.isArray()) { int index; if (currentIterationIndex > 0 && parameter.isAll()) { index = currentIterationIndex; } else { index = parameter.index; } if (!parameter.isObject()) { if (obj instanceof List) { statement.setObject(n, ((List) obj).get(index)); } else if (obj.getClass().isArray()) { Object arrayElement = Array.get(obj, index); statement.setObject(n, arrayElement); } } else { if (obj instanceof List) { statement.setObject(n, getValue(((List) obj).get(index), parameter.getFieldName())); } else if (obj.getClass().isArray()) { Object arrayElement = Array.get(obj, index); statement.setObject(n, getValue(arrayElement, parameter.getFieldName())); } } } n++; } catch (Exception e) { throw new ReadVariableException(parameter.objectName, e); } } boolean hasResultSet = statement.execute(); if (hasResultSet) { ResultSet rs = statement.getResultSet(); for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { queryResult.getColumns().add(rs.getMetaData().getColumnName(i)); queryResult.getTypes().add(rs.getMetaData().getColumnClassName(i)); } while (rs.next()) { if (rs.getMetaData().getColumnCount() != 0) { List<Object> row = new ArrayList<Object>(); queryResult.getValues().add(row); for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { if (java.sql.Date.class.getName().equals(rs.getMetaData().getColumnClassName(i))) { java.sql.Date sqlDate = rs.getDate(i); row.add(sqlDate == null ? null : new Date(sqlDate.getTime())); } else { row.add(rs.getObject(i)); } } } } } } catch (SQLException e) { //Logger.getLogger(QueryExecutor.class.getName()).log(Level.SEVERE, null, e); try { conn.rollback(); } catch (Exception e1) { //Logger.getLogger(QueryExecutor.class.getName()).log(Level.SEVERE, null, e1); } throw e; } return queryResult; }
From source file:net.sf.juffrou.reflect.JuffrouTypeConverterDelegate.java
/** * Convert the value to the required type (if necessary from a String), for the specified property. * //from www.ja va 2 s . c om * @param propertyName * name of the property * @param oldValue * the previous value, if available (may be <code>null</code>) * @param newValue * the proposed new value * @param requiredType * the type we must convert to (or <code>null</code> if not known, for example in case of a collection * element) * @param typeDescriptor * the descriptor for the target property or field * @return the new value, possibly the result of type conversion * @throws IllegalArgumentException * if type conversion failed */ @SuppressWarnings("unchecked") public <T> T convertIfNecessary(String propertyName, Object oldValue, Object newValue, Class<T> requiredType, TypeDescriptor typeDescriptor) throws IllegalArgumentException { Object convertedValue = newValue; // Custom editor for this type? PropertyEditor editor = this.propertyEditorRegistry.findCustomEditor(requiredType, propertyName); ConversionFailedException firstAttemptEx = null; // No custom editor but custom ConversionService specified? ConversionService conversionService = this.propertyEditorRegistry.getConversionService(); if (editor == null && conversionService != null && convertedValue != null && typeDescriptor != null) { TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(newValue); TypeDescriptor targetTypeDesc = typeDescriptor; if (conversionService.canConvert(sourceTypeDesc, targetTypeDesc)) { try { return (T) conversionService.convert(convertedValue, sourceTypeDesc, targetTypeDesc); } catch (ConversionFailedException ex) { // fallback to default conversion logic below firstAttemptEx = ex; } } } // Value not of required type? if (editor != null || (requiredType != null && !ClassUtils.isAssignableValue(requiredType, convertedValue))) { if (requiredType != null && Collection.class.isAssignableFrom(requiredType) && convertedValue instanceof String) { TypeDescriptor elementType = typeDescriptor.getElementTypeDescriptor(); if (elementType != null && Enum.class.isAssignableFrom(elementType.getType())) { convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue); } } if (editor == null) { editor = findDefaultEditor(requiredType); } convertedValue = doConvertValue(oldValue, convertedValue, requiredType, editor); } boolean standardConversion = false; if (requiredType != null) { // Try to apply some standard type conversion rules if appropriate. if (convertedValue != null) { if (requiredType.isArray()) { // Array required -> apply appropriate conversion of elements. if (convertedValue instanceof String && Enum.class.isAssignableFrom(requiredType.getComponentType())) { convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue); } return (T) convertToTypedArray(convertedValue, propertyName, requiredType.getComponentType()); } else if (convertedValue instanceof Collection) { // Convert elements to target type, if determined. convertedValue = convertToTypedCollection((Collection) convertedValue, propertyName, requiredType, typeDescriptor); standardConversion = true; } else if (convertedValue instanceof Map) { // Convert keys and values to respective target type, if determined. convertedValue = convertToTypedMap((Map) convertedValue, propertyName, requiredType, typeDescriptor); standardConversion = true; } if (convertedValue.getClass().isArray() && Array.getLength(convertedValue) == 1) { convertedValue = Array.get(convertedValue, 0); standardConversion = true; } if (String.class.equals(requiredType) && ClassUtils.isPrimitiveOrWrapper(convertedValue.getClass())) { // We can stringify any primitive value... return (T) convertedValue.toString(); } else if (convertedValue instanceof String && !requiredType.isInstance(convertedValue)) { if (firstAttemptEx == null && !requiredType.isInterface() && !requiredType.isEnum()) { try { Constructor strCtor = requiredType.getConstructor(String.class); return (T) BeanUtils.instantiateClass(strCtor, convertedValue); } catch (NoSuchMethodException ex) { // proceed with field lookup if (logger.isTraceEnabled()) { logger.trace("No String constructor found on type [" + requiredType.getName() + "]", ex); } } catch (Exception ex) { if (logger.isDebugEnabled()) { logger.debug( "Construction via String failed for type [" + requiredType.getName() + "]", ex); } } } String trimmedValue = ((String) convertedValue).trim(); if (requiredType.isEnum() && "".equals(trimmedValue)) { // It's an empty enum identifier: reset the enum value to null. return null; } convertedValue = attemptToConvertStringToEnum(requiredType, trimmedValue, convertedValue); standardConversion = true; } } if (!ClassUtils.isAssignableValue(requiredType, convertedValue)) { if (firstAttemptEx != null) { throw firstAttemptEx; } // Definitely doesn't match: throw IllegalArgumentException/IllegalStateException StringBuilder msg = new StringBuilder(); msg.append("Cannot convert value of type [").append(ClassUtils.getDescriptiveType(newValue)); msg.append("] to required type [").append(ClassUtils.getQualifiedName(requiredType)).append("]"); if (propertyName != null) { msg.append(" for property '").append(propertyName).append("'"); } if (editor != null) { msg.append(": PropertyEditor [").append(editor.getClass().getName()) .append("] returned inappropriate value of type [") .append(ClassUtils.getDescriptiveType(convertedValue)).append("]"); throw new IllegalArgumentException(msg.toString()); } else { msg.append(": no matching editors or conversion strategy found"); throw new IllegalStateException(msg.toString()); } } } if (firstAttemptEx != null) { if (editor == null && !standardConversion && requiredType != null && !Object.class.equals(requiredType)) { throw firstAttemptEx; } logger.debug("Original ConversionService attempt failed - ignored since " + "PropertyEditor based conversion eventually succeeded", firstAttemptEx); } return (T) convertedValue; }
From source file:com.twosigma.beakerx.sql.QueryExecutor.java
private QueryResult executeQuery(int currentIterationIndex, BeakerParseResult queryLine, Connection conn, BeakerXClient namespaceClient) throws SQLException, ReadVariableException { QueryResult queryResult = new QueryResult(); try (PreparedStatement statement = conn.prepareStatement(queryLine.getResultQuery())) { this.statement = statement; int n = 1; for (BeakerInputVar parameter : queryLine.getInputVars()) { if (parameter.getErrorMessage() != null) throw new ReadVariableException(parameter.getErrorMessage()); Object obj;// w ww . ja va 2 s. c o m try { obj = namespaceClient.get(parameter.objectName); if (!parameter.isArray() && !parameter.isObject()) { statement.setObject(n, obj); } else if (!parameter.isArray() && parameter.isObject()) { statement.setObject(n, getValue(obj, parameter.getFieldName())); } else if (parameter.isArray()) { int index; if (currentIterationIndex > 0 && parameter.isAll()) { index = currentIterationIndex; } else { index = parameter.index; } if (!parameter.isObject()) { if (obj instanceof List) { statement.setObject(n, ((List) obj).get(index)); } else if (obj.getClass().isArray()) { Object arrayElement = Array.get(obj, index); statement.setObject(n, arrayElement); } } else { if (obj instanceof List) { statement.setObject(n, getValue(((List) obj).get(index), parameter.getFieldName())); } else if (obj.getClass().isArray()) { Object arrayElement = Array.get(obj, index); statement.setObject(n, getValue(arrayElement, parameter.getFieldName())); } } } n++; } catch (Exception e) { throw new ReadVariableException(parameter.objectName, e); } } boolean hasResultSet = statement.execute(); if (hasResultSet) { ResultSet rs = statement.getResultSet(); for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { queryResult.getColumns().add(rs.getMetaData().getColumnName(i)); queryResult.getTypes().add(rs.getMetaData().getColumnClassName(i)); } while (rs.next()) { if (rs.getMetaData().getColumnCount() != 0) { List<Object> row = new ArrayList<Object>(); queryResult.getValues().add(row); for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { if (java.sql.Date.class.getName().equals(rs.getMetaData().getColumnClassName(i))) { java.sql.Date sqlDate = rs.getDate(i); row.add(sqlDate == null ? null : new Date(sqlDate.getTime())); } else { row.add(rs.getObject(i)); } } } } } } catch (SQLException e) { //Logger.getLogger(QueryExecutor.class.getName()).log(Level.SEVERE, null, e); try { conn.rollback(); } catch (Exception e1) { //Logger.getLogger(QueryExecutor.class.getName()).log(Level.SEVERE, null, e1); } throw e; } return queryResult; }
From source file:cz.zcu.kiv.eegdatabase.logic.indexing.PojoIndexer.java
/** * Creates a document for indexing. The document consists of values of fields having indexing annotations. * Depending on the annotation type, fields are either put to the document or traversed recursively to pick * property values of nested objects.//from ww w .ja va 2 s.c om * @param instance Parent object to be indexed, * @param level Current level of traversal. Can be either parent or child level. In case of the parent level, the * algorithm can continue indexing the child elements located in the child level. In both levels * indexing of String and primitive types is allowed. * @return Field-value pairs representing a document to be indexed. * @throws IllegalAccessException * @throws NoSuchMethodException * @throws InvocationTargetException */ private Map<String, Object> getDocumentFromAnnotatedFields(Object instance, int level) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { Map<String, Object> solrFields = new HashMap<String, Object>(); Field[] fields = instance.getClass().getDeclaredFields(); for (Field field : fields) { // check presence of the SolrField annotation for each field if (field.isAnnotationPresent(SolrField.class)) { field.setAccessible(true); // necessary since all fields are private Object fieldValue = field.get(instance); // actual value of the annotated field log.debug(instance.getClass().getName()); // null values are skipped if (fieldValue == null) { continue; } String fieldName = field.getAnnotation(SolrField.class).name().getValue(); if (level == LEVEL_CHILD) { fieldName = "child_" + fieldName; } log.debug("Indexing - field: " + fieldName + " value: " + fieldValue.toString()); // POJO has more fields having the same annotation parameter if (solrFields.containsKey(fieldName)) { solrFields.put(fieldName, solrFields.get(fieldName) + " " + fieldValue); } // the annotated value is being read for the first time else { solrFields.put(fieldName, fieldValue); } } // traverse collections and objects of the parent object else if (level == LEVEL_PARENT) { // check if it is a collection if (field.isAnnotationPresent(Indexed.class) && Collection.class.isAssignableFrom(field.getType())) { field.setAccessible(true); // necessary since all fields are private Object collectionInstance = field.get(instance); if (collectionInstance == null) { continue; } // convert the collection to an array to enable transparent manipulation independent // on the specific collection subclass Method objectToArray = field.getType().getMethod("toArray"); Object array = objectToArray.invoke(collectionInstance); // get array size int length = Array.getLength(array); Map<String, List<Object>> solrFieldsChildren = new HashMap<String, List<Object>>(); for (int i = 0; i < length; i++) { Object element = Array.get(array, i); // scan only the @SolrField-annotated fields of the child objects Map<String, Object> solrFieldsChild = getDocumentFromAnnotatedFields(element, LEVEL_CHILD); // add all field-value pairs of each object of the collection to the map of the whole collection for (Map.Entry<String, Object> entry : solrFieldsChild.entrySet()) { if (solrFieldsChildren.containsKey(entry.getKey())) { List<Object> list = solrFieldsChildren.get(entry.getKey()); list.add(entry.getValue()); solrFieldsChildren.put(entry.getKey(), list); } else { List<Object> list = new ArrayList<Object>(); list.add(entry.getValue()); solrFieldsChildren.put(entry.getKey(), list); } } } // add the index values of the children from the collection to the parent fields solrFields.putAll(solrFieldsChildren); } // check if it's an object else if (field.isAnnotationPresent(Indexed.class) && field.getType().isInstance(Object.class)) { // scan only the @SolrField-annotated fields of the child objects Map<String, Object> solrFieldsChild = getDocumentFromAnnotatedFields(field.get(instance), LEVEL_CHILD); solrFields.putAll(solrFieldsChild); } } } return solrFields; }
From source file:com.adf.bean.AbsBean.java
private JSONArray arrayObjectToJson(Object val) { int count = Array.getLength(val); JSONArray arr = new JSONArray(); for (int i = 0; i < count; i++) { Object obj = Array.get(val, i); arr.put(obj);// www.j av a2s. c om } return arr; }
From source file:com.exadel.flamingo.flex.messaging.amf.io.AMF3Serializer.java
protected void writeAMF3Array(Object array) throws IOException { if (debugMore) debug("writeAMF3Array(array=", array, ")"); write(AMF3_ARRAY);/*from w ww .j a v a2 s. c o m*/ int index = indexOfStoredObjects(array); if (index >= 0) writeAMF3IntegerData(index << 1); else { addToStoredObjects(array); int length = Array.getLength(array); writeAMF3IntegerData(length << 1 | 0x01); write(0x01); for (int i = 0; i < length; i++) writeObject(Array.get(array, i)); } }