Example usage for java.lang.reflect Array getLength

List of usage examples for java.lang.reflect Array getLength

Introduction

In this page you can find the example usage for java.lang.reflect Array getLength.

Prototype

@HotSpotIntrinsicCandidate
public static native int getLength(Object array) throws IllegalArgumentException;

Source Link

Document

Returns the length of the specified array object, as an int .

Usage

From source file:gda.device.scannable.ScannableUtils.java

/**
 * Performs some basic validation of the given Scannable to check for internal consistency. This should be called at
 * the end of every Scannable's constructor.
 * <p>/*from   w w w  .  j ava  2 s.c om*/
 * If the validation fails then an exception with an explanatory message is thrown.
 * 
 * @param theScannable
 * @throws ScannableUtils.ScannableValidationException
 */
public static void validate(Scannable theScannable) throws ScannableUtils.ScannableValidationException {
    int inputNamesSize = theScannable.getInputNames().length;
    int extraNamesSize = theScannable.getExtraNames().length;
    int outputFormatSize = theScannable.getOutputFormat().length;

    int positionSize = 0;
    Object position;
    try {
        position = theScannable.getPosition();
    } catch (PyException e) {
        throw new ScannableUtils.ScannableValidationException("validation error. Cannot get position string of "
                + theScannable.getName() + ": " + e.toString());
    } catch (DeviceException e) {
        throw new ScannableUtils.ScannableValidationException(
                theScannable.getName() + ": validation error. Cannot get position: " + e.getMessage());
    }

    if (position == null) {
        // do nothing as it could be a zero output scannable
    } else if (position.getClass().isArray()) {
        positionSize = Array.getLength(position);
    } else if (position instanceof PySequence) {
        positionSize = ((PySequence) position).__len__();
    } else {
        positionSize = 1;
    }

    // test that inputNames and extraNames are the same size as the
    // outputFormat array
    if ((inputNamesSize + extraNamesSize) != outputFormatSize) {
        throw new ScannableUtils.ScannableValidationException("outputFormat array of size: " + outputFormatSize
                + " but inputNames and extraNames have " + (inputNamesSize + extraNamesSize) + " elements");
    }

    // test that getPosition returns an array which is the same size
    // as the inputNames and extraNames
    if ((inputNamesSize + extraNamesSize) != positionSize) {
        throw new ScannableUtils.ScannableValidationException(
                "position is an array of size: " + outputFormatSize + " but inputNames and extraNames have "
                        + (inputNamesSize + extraNamesSize) + " elements");
    }
}

From source file:eu.qualityontime.commons.QPropertyUtilsBean.java

public Object _getIndexedProperty(final Object bean, final String name, final int index) throws Exception {

    if (bean == null) {
        throw new IllegalArgumentException("No bean specified");
    }//from w  ww.jav  a 2 s  .c om
    if (name == null || name.length() == 0) {
        if (bean.getClass().isArray()) {
            return Array.get(bean, index);
        } else if (bean instanceof List) {
            return ((List<?>) bean).get(index);
        }
    }
    if (name == null) {
        throw new IllegalArgumentException("No name specified for bean class '" + bean.getClass() + "'");
    }

    if (name.startsWith("@")) {
        Object f = FieldUtils.readField(bean, trimAnnotations(name));
        if (null == f) {
            if (name.endsWith("?"))
                return null;
            else
                throw new NestedNullException();
        }
        if (f.getClass().isArray())
            return Array.get(f, index);
        else if (f instanceof List)
            return ((List<?>) f).get(index);
    }
    // Retrieve the property descriptor for the specified property
    final PropertyDescriptor descriptor = getPropertyDescriptor(bean, trimAnnotations(name));
    if (descriptor == null) {
        throw new NoSuchMethodException(
                "Unknown property '" + name + "' on bean class '" + bean.getClass() + "'");
    }

    // Call the indexed getter method if there is one
    if (descriptor instanceof IndexedPropertyDescriptor) {
        Method readMethod = ((IndexedPropertyDescriptor) descriptor).getIndexedReadMethod();
        readMethod = MethodUtils.getAccessibleMethod(bean.getClass(), readMethod);
        if (readMethod != null) {
            final Object[] subscript = new Object[1];
            subscript[0] = new Integer(index);
            try {
                return invokeMethod(readMethod, bean, subscript);
            } catch (final InvocationTargetException e) {
                if (e.getTargetException() instanceof IndexOutOfBoundsException) {
                    throw (IndexOutOfBoundsException) e.getTargetException();
                } else {
                    throw e;
                }
            }
        }
    }

    // Otherwise, the underlying property must be an array
    final Method readMethod = getReadMethod(bean.getClass(), descriptor);
    if (readMethod == null) {
        throw new NoSuchMethodException(
                "Property '" + name + "' has no " + "getter method on bean class '" + bean.getClass() + "'");
    }

    // Call the property getter and return the value
    final Object value = invokeMethod(readMethod, bean, EMPTY_OBJECT_ARRAY);
    if (null == value && name.endsWith("?"))
        return null;
    if (!value.getClass().isArray()) {
        if (!(value instanceof java.util.List)) {
            throw new IllegalArgumentException(
                    "Property '" + name + "' is not indexed on bean class '" + bean.getClass() + "'");
        } else {
            // get the List's value
            return ((java.util.List<?>) value).get(index);
        }
    } else {
        // get the array's value
        try {
            return Array.get(value, index);
        } catch (final ArrayIndexOutOfBoundsException e) {
            throw new ArrayIndexOutOfBoundsException(
                    "Index: " + index + ", Size: " + Array.getLength(value) + " for property '" + name + "'");
        }
    }

}

From source file:microsoft.exchange.webservices.data.property.complex.UserConfigurationDictionary.java

/**
 * Validates the dictionary object (key or entry value).
 *
 * @param dictionaryObject Object to validate.
 * @throws Exception the exception//from  w w w.  j  ava2s  . c o m
 */
private void validateObject(Object dictionaryObject) throws Exception {
    // Keys may not be null but we rely on the internal dictionary to throw
    // if the key is null.
    if (dictionaryObject != null) {
        if (dictionaryObject.getClass().isArray()) {
            int length = Array.getLength(dictionaryObject);
            Class<?> wrapperType = Array.get(dictionaryObject, 0).getClass();
            Object[] newArray = (Object[]) Array.newInstance(wrapperType, length);
            for (int i = 0; i < length; i++) {
                newArray[i] = Array.get(dictionaryObject, i);
            }
            this.validateArrayObject(newArray);
        } else {
            this.validateObjectType(dictionaryObject);

        }

    } else {
        throw new NullPointerException();
    }
}

From source file:org.atricore.idbus.idojos.ldapidentitystore.LDAPIdentityStore.java

/**
 * Fetch the Ldap user attributes to be used as credentials.
 *
 * @param uid the user id for whom credentials are required
 * @return the hash map containing user credentials as name/value pairs
 * @throws NamingException LDAP error obtaining user credentials.
 *///from  w  w  w. ja va 2s  .c o  m
protected HashMap selectCredentials(String uid) throws NamingException {
    HashMap credentialResultSet = new HashMap();

    InitialLdapContext ctx = createLdapInitialContext();

    String principalUidAttrName = this.getPrincipalUidAttributeID();
    String usersCtxDN = this.getUsersCtxDN();

    // BasicAttributes matchAttrs = new BasicAttributes(true);
    // matchAttrs.put(principalUidAttrName, uid);

    String credentialQueryString = getCredentialQueryString();
    HashMap credentialQueryMap = parseQueryString(credentialQueryString);

    Iterator i = credentialQueryMap.keySet().iterator();
    List credentialAttrList = new ArrayList();
    while (i.hasNext()) {
        String o = (String) i.next();
        credentialAttrList.add(o);
    }

    String[] credentialAttr = (String[]) credentialAttrList.toArray(new String[credentialAttrList.size()]);

    try {

        // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, credentialAttr);

        // This gives more control over search behavior :
        NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + principalUidAttrName + "=" + uid + "))",
                getSearchControls());

        while (answer.hasMore()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attrs = sr.getAttributes();

            for (int j = 0; j < credentialAttr.length; j++) {

                Object credentialObject = attrs.get(credentialAttr[j]).get();
                String credentialName = (String) credentialQueryMap.get(credentialAttr[j]);
                String credentialValue = null;

                if (logger.isDebugEnabled())
                    logger.debug("Found user credential '" + credentialName + "' of type '"
                            + credentialObject.getClass().getName() + ""
                            + (credentialObject.getClass().isArray()
                                    ? "[" + Array.getLength(credentialObject) + "]"
                                    : "")
                            + "'");

                // if the attribute value is an array, cast it to byte[] and then convert to
                // String using proper encoding
                if (credentialObject.getClass().isArray()) {

                    try {
                        // Try to create a UTF-8 String, we use java.nio to handle errors in a better way.
                        // If the byte[] cannot be converted to UTF-8, we're using the credentialObject as is.
                        byte[] credentialData = (byte[]) credentialObject;
                        ByteBuffer in = ByteBuffer.allocate(credentialData.length);
                        in.put(credentialData);
                        in.flip();

                        Charset charset = Charset.forName("UTF-8");
                        CharsetDecoder decoder = charset.newDecoder();
                        CharBuffer charBuffer = decoder.decode(in);

                        credentialValue = charBuffer.toString();

                    } catch (CharacterCodingException e) {
                        if (logger.isDebugEnabled())
                            logger.debug("Can't convert credential value to String using UTF-8");
                    }

                } else if (credentialObject instanceof String) {
                    // The credential value must be a String ...
                    credentialValue = (String) credentialObject;

                }

                // Check what do we have ...
                if (credentialValue != null) {
                    // Remove any schema information from the credential value, like the {md5} prefix for passwords.
                    credentialValue = getSchemeFreeValue(credentialValue);
                    credentialResultSet.put(credentialName, credentialValue);
                } else {
                    // We have a binary credential, leave it as it is ... probably binary value.
                    credentialResultSet.put(credentialName, credentialObject);
                }

                if (logger.isDebugEnabled())
                    logger.debug("Found user credential '" + credentialName + "' with value '"
                            + (credentialValue != null ? credentialValue : credentialObject) + "'");
            }

        }
    } catch (NamingException e) {
        if (logger.isDebugEnabled())
            logger.debug("Failed to locate user", e);
    } finally {
        // Close the context to release the connection
        ctx.close();
    }

    return credentialResultSet;
}

From source file:com.zenesis.qx.remote.RequestHandler.java

/**
 * Handles dynamic changes to a qa.data.Array instance without having a complete replacement; expects a 
 * serverId, propertyName, type (one of "add", "remove", "order"), start, end, and optional array of items 
 * @param jp/*from   w ww  . j  av a2 s. co  m*/
 * @throws ServletException
 * @throws IOException
 */
protected void cmdEditArray(JsonParser jp) throws ServletException, IOException {
    // Get the basics
    int serverId = getFieldValue(jp, "serverId", Integer.class);
    String propertyName = getFieldValue(jp, "propertyName", String.class);
    String action = getFieldValue(jp, "type", String.class);
    Integer start = null;
    Integer end = null;

    if (!action.equals("replaceAll")) {
        start = getFieldValue(jp, "start", Integer.class);
        end = getFieldValue(jp, "end", Integer.class);
    }

    // Get our info
    Proxied serverObject = getProxied(serverId);
    ProxyType type = ProxyTypeManager.INSTANCE.getProxyType(serverObject.getClass());
    ProxyProperty prop = getProperty(type, propertyName);

    if (prop.getPropertyClass().isMap()) {
        Map items = null;

        // Get the optional array of items
        if (jp.nextToken() == JsonToken.FIELD_NAME && jp.getCurrentName().equals("items")
                && jp.nextToken() == JsonToken.START_OBJECT) {

            items = readMap(jp, prop.getPropertyClass().getKeyClass(), prop.getPropertyClass().getJavaType());
        }

        // Quick logging
        if (log.isInfoEnabled()) {
            String str = "";
            if (items != null)
                for (Object key : items.keySet()) {
                    if (str.length() > 0)
                        str += ", ";
                    str += String.valueOf(key) + "=" + String.valueOf(items.get(key));
                }
            log.info("edit-array: property=" + prop + ", type=" + action + ", start=" + start + ", end=" + end
                    + str);
        }

        if (action.equals("replaceAll")) {
            Map map = (Map) prop.getValue(serverObject);
            if (map == null) {
                try {
                    map = (Map) prop.getPropertyClass().getCollectionClass().newInstance();
                } catch (Exception e) {
                    throw new IllegalArgumentException(e.getMessage(), e);
                }
                prop.setValue(serverObject, map);
            }
            map.clear();
            map.putAll(items);
        } else
            throw new IllegalArgumentException("Unsupported action in cmdEditArray: " + action);

        // Because collection properties are objects and we change them without the serverObject's
        //   knowledge, we have to make sure we notify other trackers ourselves
        ProxyManager.propertyChanged(serverObject, propertyName, items, null);

        jp.nextToken();
    } else {
        // NOTE: items is an Array!!  But because it may be an array of primitive types, we have
        //   to use java.lang.reflect.Array to access members because we cannot cast arrays of
        //   primitives to Object[]
        Object items = null;

        // Get the optional array of items
        if (jp.nextToken() == JsonToken.FIELD_NAME && jp.getCurrentName().equals("items")
                && jp.nextToken() == JsonToken.START_ARRAY) {

            items = readArray(jp, prop.getPropertyClass().getJavaType());
        }
        int itemsLength = Array.getLength(items);

        // Quick logging
        if (log.isInfoEnabled()) {
            String str = "";
            if (items != null)
                for (int i = 0; i < itemsLength; i++) {
                    if (str.length() != 0)
                        str += ", ";
                    str += Array.get(items, i);
                }
            log.info("edit-array: property=" + prop + ", type=" + action + ", start=" + start + ", end=" + end
                    + str);
        }

        if (action.equals("replaceAll")) {
            if (prop.getPropertyClass().isCollection()) {
                Collection list = (Collection) prop.getValue(serverObject);
                if (list == null) {
                    try {
                        list = (Collection) prop.getPropertyClass().getCollectionClass().newInstance();
                    } catch (Exception e) {
                        throw new IllegalArgumentException(e.getMessage(), e);
                    }
                    prop.setValue(serverObject, list);
                }
                list.clear();
                if (items != null)
                    for (int i = 0; i < itemsLength; i++)
                        list.add(Array.get(items, i));

                // Because collection properties are objects and we change them without the serverObject's
                //   knowledge, we have to make sure we notify other trackers ourselves
                ProxyManager.propertyChanged(serverObject, propertyName, list, null);
            } else {
                prop.setValue(serverObject, items);
            }
        } else
            throw new IllegalArgumentException("Unsupported action in cmdEditArray: " + action);

        jp.nextToken();
    }
}

From source file:com.comphenix.protocol.events.PacketContainerTest.java

/**
 * Get the underlying array as an object array.
 * @param val - array wrapped as an Object.
 * @return An object array.//from www .j  ava  2 s  .  c o  m
 */
private Object[] getArray(Object val) {
    if (val instanceof Object[])
        return (Object[]) val;
    if (val == null)
        return null;

    int arrlength = Array.getLength(val);
    Object[] outputArray = new Object[arrlength];

    for (int i = 0; i < arrlength; ++i)
        outputArray[i] = Array.get(val, i);
    return outputArray;
}

From source file:Main.java

/**
 * Underlying implementation of add(array, index, element) methods.
 * The last parameter is the class, which may not equal element.getClass
 * for primitives./* www.ja v a  2  s  . c o  m*/
 *
 * @param array  the array to add the element to, may be {@code null}
 * @param index  the position of the new object
 * @param element  the object to add
 * @param clss the type of the element being added
 * @return A new array containing the existing elements and the new element
 */
private static Object add(Object array, int index, Object element, Class<?> clss) {
    if (array == null) {
        if (index != 0) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Length: 0");
        }
        Object joinedArray = Array.newInstance(clss, 1);
        Array.set(joinedArray, 0, element);
        return joinedArray;
    }
    int length = Array.getLength(array);
    if (index > length || index < 0) {
        throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length);
    }
    Object result = Array.newInstance(clss, length + 1);
    System.arraycopy(array, 0, result, 0, index);
    Array.set(result, index, element);
    if (index < length) {
        System.arraycopy(array, index, result, index + 1, length - index);
    }
    return result;
}

From source file:Main.java

/**
 * Underlying implementation of add(array, index, element) methods.
 * The last parameter is the class, which may not equal element.getClass
 * for primitives./*ww w.  j  a  v  a2s . c  o  m*/
 *
 * @param array  the array to add the element to, may be {@code null}
 * @param index  the position of the new object
 * @param element  the object to add
 * @param clss the type of the element being added
 * @return A new array containing the existing elements and the new element
 */
private static Object add(final Object array, final int index, final Object element, final Class<?> clss) {
    if (array == null) {
        if (index != 0) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Length: 0");
        }
        final Object joinedArray = Array.newInstance(clss, 1);
        Array.set(joinedArray, 0, element);
        return joinedArray;
    }
    final int length = Array.getLength(array);
    if (index > length || index < 0) {
        throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length);
    }
    final Object result = Array.newInstance(clss, length + 1);
    System.arraycopy(array, 0, result, 0, index);
    Array.set(result, index, element);
    if (index < length) {
        System.arraycopy(array, index, result, index + 1, length - index);
    }
    return result;
}

From source file:ArrayUtils.java

/**
 * Like {@link #containsP(Object, Object)} but the equality test is by
 * identity instead of the equals method
 * //from  w ww.j a v a  2s  .co  m
 * @param anArray
 *            The array to search
 * @param anElement
 *            The element to search for
 * @return True if <code>anArray</code> contains <code>anElement</code> by
 *         identity, false otherwise
 */
public static boolean containspID(Object anArray, Object anElement) {
    if (anArray == null)
        return false;
    if (anArray instanceof Object[]) {
        Object[] oa = (Object[]) anArray;
        for (int i = 0; i < oa.length; i++) {
            if (oa[i] == anElement)
                return true;
        }
    } else {
        int len = Array.getLength(anArray);
        for (int i = 0; i < len; i++) {
            if (Array.get(anArray, i) == anElement)
                return true;
        }
    }
    return false;
}

From source file:Main.java

/**
 * Returns a copy of the given array of size 1 greater than the argument.
 * The last value of the array is left to the default value.
 *
 * @param array The array to copy, must not be {@code null}.
 * @param newArrayComponentType If {@code array} is {@code null}, create a
 * size 1 array of this type.// w ww  . j av  a 2s . c o m
 * @return A new copy of the array of size 1 greater than the input.
 */
private static Object copyArrayGrow1(Object array, Class<?> newArrayComponentType) {
    if (array != null) {
        int arrayLength = Array.getLength(array);
        Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1);
        System.arraycopy(array, 0, newArray, 0, arrayLength);
        return newArray;
    }
    return Array.newInstance(newArrayComponentType, 1);
}