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:com.darkstar.beanCartography.utils.finder.Finder.java
/** * Process the bean context stack.//from w ww . ja va 2 s. c o m * * @param stack stack of objects left to search * @param visited set of objects already searched */ protected void visit(Deque<BeanContext> stack, Set<BeanContext> visited) { BeanContext target = stack.pop(); if (target == null) return; if (visited.contains(target)) return; visited.add(target); // process this object and check the filters. if passed filter then run interceptors... filtersInterceptors.entrySet().stream().filter(entry -> entry.getKey().accept(target.getSource())) .forEach(entry -> entry.getValue().intercept(target.getSource())); // process this object's contained objects (i.e. see what we need to add to the stack)... if (NameUtils.isImmutable(target.getSource().getClass())) return; Object fieldValue = null; try { while (target.hasNextFieldValue()) { fieldValue = target.nextFieldValue(); // skip nulls... if (fieldValue == null) continue; // add pojo or container or whatever this is... if (!visited.contains(fieldValue) && !stack.contains(fieldValue)) stack.add(new BeanContext(fieldValue)); // arrays... if (fieldValue.getClass().isArray()) { if (!processArrays) continue; final Object arrayFieldValue = fieldValue; IntStream.range(0, Array.getLength(arrayFieldValue)).forEach(i -> { Object element = Array.get(arrayFieldValue, i); if (element != null && !visited.contains(element) && !stack.contains(element)) stack.add(new BeanContext(element)); }); // collections... } else if (fieldValue instanceof Collection<?>) { if (!processCollections) continue; ((Collection<?>) fieldValue).stream().filter( element -> element != null && !visited.contains(element) && !stack.contains(element)) .forEach(element -> stack.add(new BeanContext(element))); // maps... } else if (fieldValue instanceof Map<?, ?>) { if (!processMaps) continue; ((Map<?, ?>) fieldValue).entrySet().stream().forEach(entry -> { if (entry.getKey() != null && !visited.contains(entry.getKey()) && !stack.contains(entry.getKey())) stack.add(new BeanContext(entry.getKey())); if (entry.getValue() != null && !visited.contains(entry.getValue()) && !stack.contains(entry.getValue())) stack.add(new BeanContext(entry.getValue())); }); } } } catch (Exception e) { e.printStackTrace(); } }
From source file:org.compass.gps.device.jdbc.AbstractJdbcGpsDevice.java
/** * Called for each row in the <code>ResultSet</code> which maps to an * {@link org.compass.gps.device.jdbc.AbstractJdbcGpsDevice.IndexExecution}. Can be override by derived classes, if not * override, than calls//from ww w . ja va 2 s. com * {@link #processRowValue(Object, java.sql.ResultSet, org.compass.core.CompassSession)} and uses it's * return value to save it in the <code>CompassSession</code>. The return * value can be an OSEM enables object, a <code>Resource</code>, or an * array of one of them. */ protected void processRow(Object description, ResultSet rs, CompassSession session) throws SQLException, CompassException { if (!isRunning()) { return; } Object value = processRowValue(description, rs, session); if (value != null) { if (value instanceof Object[]) { int length = Array.getLength(value); for (int i = 0; i < length; i++) { Object value1 = Array.get(value, i); session.create(value1); } } else { session.create(value); } } }
From source file:Main.java
/** * Returns the <code>index</code>-th value in <code>object</code>, throwing * <code>IndexOutOfBoundsException</code> if there is no such element or * <code>IllegalArgumentException</code> if <code>object</code> is not an * instance of one of the supported types. * <p>/*from ww w . ja v a2 s. c om*/ * The supported types, and associated semantics are: * <ul> * <li>Map -- the value returned is the <code>Map.Entry</code> in position * <code>index</code> in the map's <code>entrySet</code> iterator, if there * is such an entry.</li> * <li>List -- this method is equivalent to the list's get method.</li> * <li>Array -- the <code>index</code>-th array entry is returned, if there * is such an entry; otherwise an <code>IndexOutOfBoundsException</code> is * thrown.</li> * <li>Collection -- the value returned is the <code>index</code>-th object * returned by the collection's default iterator, if there is such an * element.</li> * <li>Iterator or Enumeration -- the value returned is the * <code>index</code>-th object in the Iterator/Enumeration, if there is * such an element. The Iterator/Enumeration is advanced to * <code>index</code> (or to the end, if <code>index</code> exceeds the * number of entries) as a side effect of this method.</li> * </ul> * * @param object * the object to get a value from * @param index * the index to get * @return the object at the specified index * @throws IndexOutOfBoundsException * if the index is invalid * @throws IllegalArgumentException * if the object type is invalid */ public static Object get(Object object, int index) { if (index < 0) { throw new IndexOutOfBoundsException("Index cannot be negative: " + index); } if (object instanceof Map) { Map<?, ?> map = (Map<?, ?>) object; Iterator<?> iterator = map.entrySet().iterator(); return get(iterator, index); } else if (object instanceof List) { return ((List<?>) object).get(index); } else if (object instanceof Object[]) { return ((Object[]) object)[index]; } else if (object instanceof Iterator) { Iterator<?> it = (Iterator<?>) object; while (it.hasNext()) { index--; if (index == -1) { return it.next(); } else { it.next(); } } throw new IndexOutOfBoundsException("Entry does not exist: " + index); } else if (object instanceof Collection) { Iterator<?> iterator = ((Collection<?>) object).iterator(); return get(iterator, index); } else if (object instanceof Enumeration) { Enumeration<?> it = (Enumeration<?>) object; while (it.hasMoreElements()) { index--; if (index == -1) { return it.nextElement(); } else { it.nextElement(); } } throw new IndexOutOfBoundsException("Entry does not exist: " + index); } else if (object == null) { throw new IllegalArgumentException("Unsupported object type: null"); } else { try { return Array.get(object, index); } catch (IllegalArgumentException ex) { throw new IllegalArgumentException("Unsupported object type: " + object.getClass().getName()); } } }
From source file:org.ebayopensource.common.util.DataUtil.java
public static String[] getStringArray(Object object, String[] defValue) { if (object == null) { return defValue; }/*from www. j a v a2 s . com*/ String[] result; if (object instanceof String[]) { result = (String[]) object; } else if (object instanceof String) { String str = (String) object; str = str.trim(); result = StringUtils.split(str, ','); } else if (object instanceof Object[]) { Object[] array = (Object[]) object; result = new String[array.length]; for (int i = 0; i < array.length; i++) { result[i] = getString(array[i], null); } } else if (object instanceof List) { List list = (List) object; result = new String[list.size()]; for (int i = 0; i < list.size(); i++) { result[i] = getString(list.get(i), null); } } else if (object.getClass().isArray()) { int len = Array.getLength(object); result = new String[len]; for (int i = 0; i < len; i++) { result[i] = getString(Array.get(object, i), null); } } else if (object instanceof Number || object instanceof Boolean || object instanceof Character) { result = new String[] { object.toString() }; } else { result = defValue; } return result; }
From source file:org.jbpm.formModeler.core.processing.fieldHandlers.CreateDynamicObjectFieldFormatter.java
protected void editItemInPosition(Form parentForm, String currentNamespace, int position, Field field, Object value, String fieldName) { if (value != null) { if (value.getClass().isArray()) { CreateDynamicObjectFieldHandler fieldHandler = (CreateDynamicObjectFieldHandler) getFieldHandlersManager() .getHandler(field.getFieldType()); Form formToEdit = fieldHandler.getEditForm(field, currentNamespace); Map valueToEdit = (Map) Array.get(value, position); if (formToEdit != null) { setAttribute("valueToEdit", valueToEdit); setAttribute("name", fieldName); setAttribute("form", formToEdit); setAttribute("uid", fieldUID); setAttribute("index", position); setAttribute("parentFormId", parentForm.getId()); setAttribute("namespace", fieldNS); setAttribute("parentNamespace", currentNamespace); setAttribute("field", field.getFieldName()); // Override the field's own disabled and readonly values with the ones coming from a parent formatter // that contains it if they're set to true. if (isReadonly) setAttribute("readonly", isReadonly); String rowNamespace = fieldNS + FormProcessor.CUSTOM_NAMESPACE_SEPARATOR + position; getFormProcessor().clear(formToEdit, rowNamespace); getFormProcessor().read(formToEdit, rowNamespace, valueToEdit); renderFragment("editItem"); }/* w w w. j a va 2 s . c o m*/ } } }
From source file:com.ctriposs.rest4j.client.Request.java
/** * Returns a read only version of {@code value} * @param value the object we want to get a read only version of * @return a read only version of {@code value} *///from w w w . j ava2 s .c o m private Object getReadOnly(Object value) { if (value == null) { return null; } if (value instanceof Object[]) { // array of non-primitives Object[] arr = (Object[]) value; List<Object> list = new ArrayList<Object>(arr.length); for (Object o : arr) { list.add(getReadOnly(o)); } return Collections.unmodifiableList(list); } else if (value.getClass().isArray()) { // array of primitives int length = Array.getLength(value); List<Object> list = new ArrayList<Object>(); for (int i = 0; i < length; i++) { list.add(Array.get(value, i)); } return Collections.unmodifiableList(list); } else if (value instanceof ComplexResourceKey) { ((ComplexResourceKey) value).makeReadOnly(); return value; } else if (value instanceof CompoundKey) { ((CompoundKey) value).makeReadOnly(); return value; } else if (value instanceof DataTemplate) { Object data = ((DataTemplate) value).data(); if (data instanceof DataComplex) { ((DataComplex) data).makeReadOnly(); } // we don't try to make other types of data read only. return value; } else if (value instanceof Iterable) { List<Object> list = new ArrayList<Object>(); for (Object o : (Iterable) value) { list.add(getReadOnly(o)); } return Collections.unmodifiableList(list); } return value; }
From source file:org.apache.commons.httpclient.contrib.proxy.PluginProxyUtil.java
/** * Returns the proxy information for the specified sampleURL using JRE 1.4+ * specific plugin classes./* w w w.j ava 2 s . c o m*/ * * Notes: * Plugin 1.4+ Final added * com.sun.java.browser.net.* classes ProxyInfo & ProxyService... * Use those with JREs => 1.4+ * * @param sampleURL the URL to check proxy settings for * @return ProxyHost the host and port of the proxy that should be used */ private static HttpHost detectProxySettingsJDK14_JDK15_JDK16(URL sampleURL) { HttpHost result = null; try { // Look around for the 1.4+ plugin proxy detection class... // Without it, cannot autodetect... Class<?> ProxyServiceClass = Class.forName("com.sun.java.browser.net.ProxyService"); Method getProxyInfoMethod = ProxyServiceClass.getDeclaredMethod("getProxyInfo", new Class[] { URL.class }); Object proxyInfoArrayObj = getProxyInfoMethod.invoke(null, new Object[] { sampleURL }); if (proxyInfoArrayObj == null || Array.getLength(proxyInfoArrayObj) == 0) { if (LOG.isDebugEnabled()) { LOG.debug("1.4+ reported NULL proxy (no proxy assumed)"); } result = NO_PROXY_HOST; } else { Object proxyInfoObject = Array.get(proxyInfoArrayObj, 0); Class<?> proxyInfoClass = proxyInfoObject.getClass(); Method getHostMethod = proxyInfoClass.getDeclaredMethod("getHost", (Class[]) null); String proxyIP = (String) getHostMethod.invoke(proxyInfoObject, (Object[]) null); Method getPortMethod = proxyInfoClass.getDeclaredMethod("getPort", (Class[]) null); Integer portInteger = (Integer) getPortMethod.invoke(proxyInfoObject, (Object[]) null); int proxyPort = portInteger.intValue(); if (LOG.isDebugEnabled()) { LOG.debug("1.4+ Proxy info get Proxy:" + proxyIP + " get Port:" + proxyPort); } result = new HttpHost(proxyIP, proxyPort); } } catch (RuntimeException e) { throw e; } catch (Exception e) { LOG.debug("Sun Plugin 1.4+ proxy detection class not found, " + "will try failover detection" /*, e*/); } return result; }
From source file:com.krawler.br.exp.Variable.java
private void setIndexedElement(Object cont, int index, Object val, boolean insert) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, ProcessException { if (cont == null) { throw new ProcessException("container not found for variable: " + this); } else {/* www . j a v a2s .co m*/ if (indices != null && indices.containsKey(index)) { Iterator<Expression> itr = indices.get(index).iterator(); Object container = null; while (cont != null && itr.hasNext()) { container = cont; int idx = ((Number) itr.next().getValue()).intValue(); if (itr.hasNext()) { if (cont instanceof JSONArray) { cont = ((JSONArray) cont).opt(idx); } else if (cont instanceof java.util.List) { cont = ((java.util.List) cont).get(idx); } else if (cont.getClass().isArray()) { cont = Array.get(cont, idx); } else throw new ProcessException("Unsuported container type found in variable: " + this); } else { if (container == null) throw new ProcessException("container not found for variable: " + this); else if (container instanceof JSONArray) { try { JSONArray jArr = (JSONArray) container; int last = jArr.length(); if (insert) { jArr.put(val); } if (insert && last > idx) { jArr.put(last, jArr.get(last - 1)); last--; } jArr.put(idx, val); } catch (JSONException ex) { throw new ProcessException(ex); } } else if (container instanceof java.util.List) { java.util.List list = (java.util.List) container; if (idx == list.size()) { list.add(val); } else if (insert) { list.add(idx, val); } else { list.set(idx, val); } } else if (container.getClass().isArray()) { Array.set(container, idx, val); } break; } } } } }
From source file:me.code4fun.roboq.Request.java
protected HttpUriRequest createHttpRequest(int method, String url, Options opts) { String url1 = makeUrl(url, opts); // Create HTTP request HttpUriRequest httpReq;//from w w w . j a va 2 s . c o m if (GET == method) { httpReq = new HttpGet(url1); } else if (POST == method) { httpReq = new HttpPost(url1); } else if (PUT == method) { httpReq = new HttpPut(url1); } else if (DELETE == method) { httpReq = new HttpDelete(url1); } else if (TRACE == method) { httpReq = new HttpTrace(url1); } else if (HEAD == method) { httpReq = new HttpHead(url1); } else if (OPTIONS == method) { httpReq = new HttpOptions(url1); } else { throw new IllegalStateException("Illegal HTTP method " + method); } // Set headers Map<String, Object> headers = opts.getHeaders(); for (Map.Entry<String, Object> entry : headers.entrySet()) { String k = entry.getKey(); Object v = entry.getValue(); if (v != null && v.getClass().isArray()) { int len = Array.getLength(v); for (int i = 0; i < len; i++) { Object v0 = Array.get(v, i); httpReq.addHeader(k, o2s(v0, "")); } } else if (v instanceof List) { for (Object v0 : (List) v) httpReq.addHeader(k, o2s(v0, "")); } else { httpReq.addHeader(k, o2s(v, "")); } } // set body if (httpReq instanceof HttpEntityEnclosingRequestBase) { ((HttpEntityEnclosingRequestBase) httpReq).setEntity(createRequestBody(method, url, opts)); } return httpReq; }
From source file:com.espertech.esper.epl.annotation.AnnotationUtil.java
private static Object getFinalValue(Class annotationClass, AnnotationAttribute annotationAttribute, Object value, EngineImportService engineImportService) throws AnnotationException { if (value == null) { if (annotationAttribute.getDefaultValue() == null) { throw new AnnotationException("Annotation '" + annotationClass.getSimpleName() + "' requires a value for attribute '" + annotationAttribute.getName() + "'"); }/*w w w . j a v a 2 s . c o m*/ return annotationAttribute.getDefaultValue(); } // handle non-array if (!annotationAttribute.getType().isArray()) { // handle primitive value if (!annotationAttribute.getType().isAnnotation()) { SimpleTypeCaster caster = SimpleTypeCasterFactory.getCaster(value.getClass(), annotationAttribute.getType()); Object finalValue = caster.cast(value); if (finalValue == null) { throw new AnnotationException("Annotation '" + annotationClass.getSimpleName() + "' requires a " + annotationAttribute.getType().getSimpleName() + "-typed value for attribute '" + annotationAttribute.getName() + "' but received " + "a " + value.getClass().getSimpleName() + "-typed value"); } return finalValue; } else { // nested annotation if (!(value instanceof AnnotationDesc)) { throw new AnnotationException("Annotation '" + annotationClass.getSimpleName() + "' requires a " + annotationAttribute.getType().getSimpleName() + "-typed value for attribute '" + annotationAttribute.getName() + "' but received " + "a " + value.getClass().getSimpleName() + "-typed value"); } return createProxy((AnnotationDesc) value, engineImportService); } } if (!value.getClass().isArray()) { throw new AnnotationException("Annotation '" + annotationClass.getSimpleName() + "' requires a " + annotationAttribute.getType().getSimpleName() + "-typed value for attribute '" + annotationAttribute.getName() + "' but received " + "a " + value.getClass().getSimpleName() + "-typed value"); } Object array = Array.newInstance(annotationAttribute.getType().getComponentType(), Array.getLength(value)); for (int i = 0; i < Array.getLength(value); i++) { Object arrayValue = Array.get(value, i); if (arrayValue == null) { throw new AnnotationException("Annotation '" + annotationClass.getSimpleName() + "' requires a " + "non-null value for array elements for attribute '" + annotationAttribute.getName() + "'"); } SimpleTypeCaster caster = SimpleTypeCasterFactory.getCaster(arrayValue.getClass(), annotationAttribute.getType().getComponentType()); Object finalValue = caster.cast(arrayValue); if (finalValue == null) { throw new AnnotationException("Annotation '" + annotationClass.getSimpleName() + "' requires a " + annotationAttribute.getType().getComponentType().getSimpleName() + "-typed value for array elements for attribute '" + annotationAttribute.getName() + "' but received " + "a " + arrayValue.getClass().getSimpleName() + "-typed value"); } Array.set(array, i, finalValue); } return array; }