Example usage for java.lang.reflect Array get

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

Introduction

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

Prototype

public static native Object get(Object array, int index)
        throws IllegalArgumentException, ArrayIndexOutOfBoundsException;

Source Link

Document

Returns the value of the indexed component in the specified array object.

Usage

From source file:ArrayUtils.java

/**
 * Gets the elements that are in array2, but not array 1.
 * /*from  ww w  .  j  a v  a2  s . c  o m*/
 * @param array1
 *            The first array
 * @param array2
 *            The second array
 * @return The elements in <code>array2</code> that do not occur in
 *         <code>array1</code>
 */
public static Object[] addedElements(Object array1, Object array2) {
    int count = 0;
    if (array1 == null || array2 == null)
        return new Object[0];
    if (!array1.getClass().isArray() || array2.getClass().isArray())
        return new Object[0];
    int len1 = Array.getLength(array1);
    int len2 = Array.getLength(array2);
    int i, j;
    for (i = 0; i < len1; i++) {
        count++;
        for (j = 0; j < len2; j++) {
            if (equals(Array.get(array2, i), Array.get(array1, j))) {
                count--;
                break;
            }
        }
    }
    Object[] ret = new Object[count];
    count = 0;
    for (i = 0; i < len1; i++) {
        count++;
        for (j = 0; j < len2; j++) {
            if (equals(Array.get(array2, i), Array.get(array1, j))) {
                count--;
                break;
            }
            ret[count] = Array.get(array2, i);
        }
    }
    return ret;
}

From source file:net.yasion.common.core.bean.wrapper.impl.ExtendedBeanWrapperImpl.java

@SuppressWarnings("unchecked")
private void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv2) throws BeansException {
    net.yasion.common.core.bean.wrapper.PropertyValue pv = new net.yasion.common.core.bean.wrapper.PropertyValue(
            "", null);
    AfxBeanUtils.copySamePropertyValue(pv2, pv);
    String propertyName = tokens.canonicalName;
    String actualName = tokens.actualName;

    if (tokens.keys != null) {
        // Apply indexes and map keys: fetch value for all keys but the last one.
        PropertyTokenHolder getterTokens = new PropertyTokenHolder();
        getterTokens.canonicalName = tokens.canonicalName;
        getterTokens.actualName = tokens.actualName;
        getterTokens.keys = new String[tokens.keys.length - 1];
        System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1);
        Object propValue;//from w ww  .java2  s.  c  o  m
        try {
            propValue = getPropertyValue(getterTokens);
        } catch (NotReadablePropertyException ex) {
            throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Cannot access indexed value in property referenced " + "in indexed property path '"
                            + propertyName + "'",
                    ex);
        }
        // Set value for last key.
        String key = tokens.keys[tokens.keys.length - 1];
        if (propValue == null) {
            // null map value case
            if (isAutoGrowNestedPaths()) {
                // #TO#DO#: cleanup, this is pretty hacky
                int lastKeyIndex = tokens.canonicalName.lastIndexOf('[');
                getterTokens.canonicalName = tokens.canonicalName.substring(0, lastKeyIndex);
                propValue = setDefaultValue(getterTokens);
            } else {
                throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
                        "Cannot access indexed value in property referenced " + "in indexed property path '"
                                + propertyName + "': returned null");
            }
        }
        if (propValue.getClass().isArray()) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class<?> requiredType = propValue.getClass().getComponentType();
            int arrayIndex = Integer.parseInt(key);
            Object oldValue = null;
            try {
                if (isExtractOldValueForEditor() && arrayIndex < Array.getLength(propValue)) {
                    oldValue = Array.get(propValue, arrayIndex);
                }
                Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
                        TypeDescriptor.nested(property(pd), tokens.keys.length));
                Array.set(propValue, arrayIndex, convertedValue);
            } catch (IndexOutOfBoundsException ex) {
                throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                        "Invalid array index in property path '" + propertyName + "'", ex);
            }
        } else if (propValue instanceof List) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class<?> requiredType = GenericCollectionTypeResolver.getCollectionReturnType(pd.getReadMethod(),
                    tokens.keys.length);
            List<Object> list = (List<Object>) propValue;
            int index = Integer.parseInt(key);
            Object oldValue = null;
            if (isExtractOldValueForEditor() && index < list.size()) {
                oldValue = list.get(index);
            }
            Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
                    TypeDescriptor.nested(property(pd), tokens.keys.length));
            int size = list.size();
            if (index >= size && index < this.autoGrowCollectionLimit) {
                for (int i = size; i < index; i++) {
                    try {
                        list.add(null);
                    } catch (NullPointerException ex) {
                        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                                "Cannot set element with index " + index + " in List of size " + size
                                        + ", accessed using property path '" + propertyName
                                        + "': List does not support filling up gaps with null elements");
                    }
                }
                list.add(convertedValue);
            } else {
                try {
                    list.set(index, convertedValue);
                } catch (IndexOutOfBoundsException ex) {
                    throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                            "Invalid list index in property path '" + propertyName + "'", ex);
                }
            }
        } else if (propValue instanceof Map) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class<?> mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(pd.getReadMethod(),
                    tokens.keys.length);
            Class<?> mapValueType = GenericCollectionTypeResolver.getMapValueReturnType(pd.getReadMethod(),
                    tokens.keys.length);
            Map<Object, Object> map = (Map<Object, Object>) propValue;
            // IMPORTANT: Do not pass full property name in here - property editors
            // must not kick in for map keys but rather only for map values.
            TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(mapKeyType);
            Object convertedMapKey = convertIfNecessary(null, null, key, mapKeyType, typeDescriptor);
            Object oldValue = null;
            if (isExtractOldValueForEditor()) {
                oldValue = map.get(convertedMapKey);
            }
            // Pass full property name and old value in here, since we want full
            // conversion ability for map values.
            Object convertedMapValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), mapValueType,
                    TypeDescriptor.nested(property(pd), tokens.keys.length));
            map.put(convertedMapKey, convertedMapValue);
        } else {
            throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Property referenced in indexed property path '" + propertyName
                            + "' is neither an array nor a List nor a Map; returned value was [" + pv.getValue()
                            + "]");
        }
    }

    else {
        PropertyDescriptor pd = pv.getResolvedDescriptor();
        if (pd == null || !pd.getWriteMethod().getDeclaringClass().isInstance(this.object)) {
            pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            if (pd == null || pd.getWriteMethod() == null) {
                if (pv.isOptional()) {
                    logger.debug("Ignoring optional value for property '" + actualName
                            + "' - property not found on bean class [" + getRootClass().getName() + "]");
                    return;
                } else {
                    PropertyMatches matches = PropertyMatches.forProperty(propertyName, getRootClass());
                    throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
                            matches.buildErrorMessage(), matches.getPossibleMatches());
                }
            }
            pv.getOriginalPropertyValue().setResolvedDescriptor(pd);
        }

        Object oldValue = null;
        try {
            Object originalValue = pv.getValue();
            Object valueToApply = originalValue;
            if (!Boolean.FALSE.equals(pv.getConversionNecessary())) {
                if (pv.isConverted()) {
                    valueToApply = pv.getConvertedValue();
                } else {
                    if (isExtractOldValueForEditor() && pd.getReadMethod() != null) {
                        final Method readMethod = pd.getReadMethod();
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())
                                && !readMethod.isAccessible()) {
                            if (System.getSecurityManager() != null) {
                                AccessController.doPrivileged(new PrivilegedAction<Object>() {
                                    @Override
                                    public Object run() {
                                        readMethod.setAccessible(true);
                                        return null;
                                    }
                                });
                            } else {
                                readMethod.setAccessible(true);
                            }
                        }
                        try {
                            if (System.getSecurityManager() != null) {
                                oldValue = AccessController
                                        .doPrivileged(new PrivilegedExceptionAction<Object>() {
                                            @Override
                                            public Object run() throws Exception {
                                                return readMethod.invoke(object);
                                            }
                                        }, acc);
                            } else {
                                oldValue = readMethod.invoke(object);
                            }
                        } catch (Exception ex) {
                            if (ex instanceof PrivilegedActionException) {
                                ex = ((PrivilegedActionException) ex).getException();
                            }
                            if (logger.isDebugEnabled()) {
                                logger.debug("Could not read previous value of property '" + this.nestedPath
                                        + propertyName + "'", ex);
                            }
                        }
                    }
                    valueToApply = convertForProperty(propertyName, oldValue, originalValue,
                            new TypeDescriptor(property(pd)));
                }
                pv.getOriginalPropertyValue().setConversionNecessary(valueToApply != originalValue);
            }
            final Method writeMethod = (pd instanceof GenericTypeAwarePropertyDescriptor
                    ? ((GenericTypeAwarePropertyDescriptor) pd).getWriteMethodForActualAccess()
                    : pd.getWriteMethod());
            if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())
                    && !writeMethod.isAccessible()) {
                if (System.getSecurityManager() != null) {
                    AccessController.doPrivileged(new PrivilegedAction<Object>() {
                        @Override
                        public Object run() {
                            writeMethod.setAccessible(true);
                            return null;
                        }
                    });
                } else {
                    writeMethod.setAccessible(true);
                }
            }
            final Object value = valueToApply;
            if (System.getSecurityManager() != null) {
                try {
                    AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                        @Override
                        public Object run() throws Exception {
                            writeMethod.invoke(object, value);
                            return null;
                        }
                    }, acc);
                } catch (PrivilegedActionException ex) {
                    throw ex.getException();
                }
            } else {
                writeMethod.invoke(this.object, value);
            }
        } catch (TypeMismatchException ex) {
            throw ex;
        } catch (InvocationTargetException ex) {
            PropertyChangeEvent propertyChangeEvent = new PropertyChangeEvent(this.rootObject,
                    this.nestedPath + propertyName, oldValue, pv.getValue());
            if (ex.getTargetException() instanceof ClassCastException) {
                throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(),
                        ex.getTargetException());
            } else {
                throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException());
            }
        } catch (Exception ex) {
            PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName,
                    oldValue, pv.getValue());
            throw new MethodInvocationException(pce, ex);
        }
    }
}

From source file:gda.data.metadata.NXMetaDataProvider.java

public Object[] separateGetPositionOutputIntoElementalPosObjects(Object scannableGetPositionOut) {
    if (scannableGetPositionOut == null)
        return new Object[] {};

    Object[] elements = new Object[] { scannableGetPositionOut };
    if (scannableGetPositionOut instanceof Object[]) {
        elements = (Object[]) scannableGetPositionOut;
    } else if (scannableGetPositionOut instanceof PySequence) {
        PySequence seq = (PySequence) scannableGetPositionOut;
        int len = seq.__len__();
        elements = new Object[len];
        for (int i = 0; i < len; i++) {
            elements[i] = seq.__finditem__(i);
        }/*from ww  w.j  a  v  a2 s .c  o  m*/
    } else if (scannableGetPositionOut instanceof PyList) {
        PyList seq = (PyList) scannableGetPositionOut;
        int len = seq.__len__();
        elements = new Object[len];
        for (int i = 0; i < len; i++) {
            elements[i] = seq.__finditem__(i);
        }
    } else if (scannableGetPositionOut.getClass().isArray()) {
        int len = ArrayUtils.getLength(scannableGetPositionOut);
        elements = new Object[len];
        for (int i = 0; i < len; i++) {
            elements[i] = Array.get(scannableGetPositionOut, i);
        }
    } else if (scannableGetPositionOut instanceof PlottableDetectorData) {
        elements = ((PlottableDetectorData) scannableGetPositionOut).getDoubleVals();
    }
    return elements;
}

From source file:org.nextframework.controller.ExtendedBeanWrapper.java

protected void setPropertyValue(PropertyTokenHolder tokens, Object newValue) throws BeansException {
    String propertyName = tokens.canonicalName;

    if (tokens.keys != null) {
        // apply indexes and map keys: fetch value for all keys but the last one
        PropertyTokenHolder getterTokens = new PropertyTokenHolder();
        getterTokens.canonicalName = tokens.canonicalName;
        getterTokens.actualName = tokens.actualName;
        getterTokens.keys = new String[tokens.keys.length - 1];
        System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1);
        Object propValue = null;// www. ja  va 2  s.  c o  m
        Type type;
        try {
            propValue = getPropertyValue(getterTokens);
            type = getPropertyType(getterTokens);
            if (propValue == null) {
                Class rawType = null;
                if (type instanceof ParameterizedType) {
                    if (((ParameterizedType) type).getRawType() instanceof Class) {
                        rawType = (Class) ((ParameterizedType) type).getRawType();
                    } else if (type instanceof Class) {
                        rawType = (Class) type;
                    }
                }
                if (rawType != null && List.class.isAssignableFrom(rawType)) {
                    PropertyTokenHolder propertyTokenHolder = new PropertyTokenHolder();
                    propertyTokenHolder.actualName = getterTokens.actualName;
                    propertyTokenHolder.canonicalName = getterTokens.canonicalName;
                    setPropertyValue(propertyTokenHolder, new ArrayList());
                }
            }
        } catch (NotReadablePropertyException ex) {
            throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Cannot access indexed value in property referenced " + "in indexed property path '"
                            + propertyName + "'",
                    ex);
        }
        // set value for last key
        String key = tokens.keys[tokens.keys.length - 1];
        if (propValue == null) {
            throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
                    "Cannot access indexed value in property referenced " + "in indexed property path '"
                            + propertyName + "': returned null");
        } else if (propValue.getClass().isArray()) {
            Class requiredType = propValue.getClass().getComponentType();
            int arrayIndex = Integer.parseInt(key);
            Object oldValue = null;
            try {
                if (this.extractOldValueForEditor) {
                    oldValue = Array.get(propValue, arrayIndex);
                }
                Object convertedValue = doTypeConversionIfNecessary(propertyName, propertyName, oldValue,
                        newValue, requiredType);
                Array.set(propValue, Integer.parseInt(key), convertedValue);
            } catch (IllegalArgumentException ex) {
                PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject,
                        this.nestedPath + propertyName, oldValue, newValue);
                throw new TypeMismatchException(pce, requiredType, ex);
            } catch (IndexOutOfBoundsException ex) {
                throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                        "Invalid array index in property path '" + propertyName + "'", ex);
            }
        } else if (propValue instanceof List) {
            List list = (List) propValue;
            int index = Integer.parseInt(key);
            Object oldValue = null;
            if (this.extractOldValueForEditor && index < list.size()) {
                oldValue = list.get(index);
            }
            Object convertedValue = doTypeConversionIfNecessary(propertyName, propertyName, oldValue, newValue,
                    null);
            if (index < list.size()) {
                list.set(index, convertedValue);
            } else if (index >= list.size()) {
                for (int i = list.size(); i < index; i++) {
                    try {
                        list.add(null);
                    } catch (NullPointerException ex) {
                        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                                "Cannot set element with index " + index + " in List of size " + list.size()
                                        + ", accessed using property path '" + propertyName
                                        + "': List does not support filling up gaps with null elements");
                    }
                }
                list.add(convertedValue);
            }
        } else if (propValue instanceof Map) {
            Map map = (Map) propValue;
            propValue.getClass().getGenericSuperclass();
            Object oldValue = null;
            if (this.extractOldValueForEditor) {
                oldValue = map.get(key);
            }
            Type type2 = ((ParameterizedType) type).getActualTypeArguments()[1];
            Type type3 = ((ParameterizedType) type).getActualTypeArguments()[0];
            Class reqClass = null;
            Class keyReqClass = null;
            if (type2 instanceof Class) {
                reqClass = (Class) type2;
            } else if (type2 instanceof ParameterizedType) {
                reqClass = (Class) ((ParameterizedType) type2).getRawType();
            }

            if (type3 instanceof Class) {
                keyReqClass = (Class) type3;
            } else if (type3 instanceof ParameterizedType) {
                keyReqClass = (Class) ((ParameterizedType) type3).getRawType();
            }
            Object convertedValue = doTypeConversionIfNecessary(propertyName, propertyName, oldValue, newValue,
                    reqClass);
            Object convertedKey = doTypeConversionIfNecessary(key, keyReqClass);
            map.put(convertedKey, convertedValue);
        } else {
            throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Property referenced in indexed property path '" + propertyName
                            + "' is neither an array nor a List nor a Map; returned value was [" + newValue
                            + "]");
        }
    }

    else {
        PropertyDescriptor pd = getPropertyDescriptorInternal(propertyName);
        if (pd == null || pd.getWriteMethod() == null) {
            throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName);
        }

        Method readMethod = pd.getReadMethod();
        Method writeMethod = pd.getWriteMethod();
        Object oldValue = null;

        if (this.extractOldValueForEditor && readMethod != null) {
            try {
                oldValue = readMethod.invoke(this.object, new Object[0]);
            } catch (Exception ex) {
                logger.debug("Could not read previous value of property '" + this.nestedPath + propertyName,
                        ex);
            }
        }

        try {
            Object convertedValue = doTypeConversionIfNecessary(propertyName, propertyName, oldValue, newValue,
                    pd.getPropertyType());

            if (pd.getPropertyType().isPrimitive() && (convertedValue == null || "".equals(convertedValue))) {
                throw new IllegalArgumentException("Invalid value [" + newValue + "] for property '"
                        + pd.getName() + "' of primitive type [" + pd.getPropertyType() + "]");
            }

            if (logger.isDebugEnabled()) {
                logger.debug("About to invoke write method [" + writeMethod + "] on object of class ["
                        + this.object.getClass().getName() + "]");
            }
            writeMethod.invoke(this.object, new Object[] { convertedValue });
            if (logger.isDebugEnabled()) {
                logger.debug("Invoked write method [" + writeMethod + "] with value of type ["
                        + pd.getPropertyType().getName() + "]");
            }
        } catch (InvocationTargetException ex) {
            PropertyChangeEvent propertyChangeEvent = new PropertyChangeEvent(this.rootObject,
                    this.nestedPath + propertyName, oldValue, newValue);
            if (ex.getTargetException() instanceof ClassCastException) {
                throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(),
                        ex.getTargetException());
            } else {
                throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException());
            }
        } catch (IllegalArgumentException ex) {
            PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName,
                    oldValue, newValue);
            throw new TypeMismatchException(pce, pd.getPropertyType(), ex);
        } catch (IllegalAccessException ex) {
            PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName,
                    oldValue, newValue);
            throw new MethodInvocationException(pce, ex);
        }
    }
}

From source file:ArrayUtils.java

/**
 * Reverses the order of an array. Similar to {@link #reverse(Object[])} but
 * works for primitive arrays as well./*from   ww  w .j  av a 2  s  .c  o m*/
 * 
 * @param array
 *            The array to reverse
 * @return The reversed array, same as the original reference
 */
public static Object reverseP(Object array) {
    if (array == null)
        return array;
    if (array instanceof Object[])
        return reverse((Object[]) array);
    Object temp;
    final int aLen = Array.getLength(array);
    for (int i = 0; i < aLen / 2; i++) {
        temp = Array.get(array, i);
        put(array, Array.get(array, aLen - i - 1), i);
        put(array, temp, aLen - i - 1);
    }
    return array;
}

From source file:org.cosmo.common.util.Util.java

public static long averageDelta(Object array) {
    long[] nums = new long[Array.getLength(array)];

    if (nums.length < 2) {
        return 0;
    }//from   w w w.j a  v a 2s  . c o  m

    for (int i = 0; i < nums.length; i++) {
        nums[i] = ((Number) Array.get(array, i)).longValue();
    }

    Arrays.sort(nums);
    long totalDelta = 0;
    for (int i = nums.length - 1; i > 0; i--) {
        totalDelta += nums[i] - nums[i - 1];
    }
    return (long) ((long) totalDelta / (long) (nums.length - 1));
}

From source file:org.energy_home.jemma.ah.internal.configurator.Configuratore.java

public void exportConfiguration(OutputStream os) throws Exception {
    // Ottiene un riferimento al servizio Configuration Admin
    ServiceReference sr = bc.getServiceReference(ConfigurationAdmin.class.getName());
    ConfigurationAdmin configurationAdmin = (ConfigurationAdmin) bc.getService(sr);

    // test();//  w  w  w. j  ava  2 s  . c o m

    // Ottiene un array contenente tutte le configurazioni salvate nel
    // Configuration Admin
    Configuration[] configs = configurationAdmin.listConfigurations(null);

    // Stampa nello stream di output il file XML
    PrintWriter pw = new PrintWriter(os);
    pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
    pw.println("<configurations>");

    // Export delle categories
    if (hacService != null) {
        ICategory[] categories = hacService.getCategories();
        if (categories != null) {
            pw.println("<categories>");
            for (int i = 0; i < categories.length; i++) {
                ICategory c = categories[i];
                pw.println("<category icon=\"" + c.getIconName() + "\" name = \"" + c.getName() + "\" pid = \""
                        + c.getPid() + "\"/>");
            }
            pw.println("</categories>");
        }
    }

    // Export delle rules
    if (connAdmin != null) {
        ArrayList rules = connAdmin.getBindRules();
        if (rules != null) {
            pw.println("<rules>");
            for (int i = 0; i < rules.size(); i++) {
                Filter f = (Filter) rules.get(i);
                pw.println("<rule filter =\"" + this.xmlContentEscape(f.toString()) + "\"/>");
            }
            pw.println("</rules>");
        }
    }

    // Export delle configurazioni
    if (configs != null && configs.length > 0) {
        Set factories = new HashSet();
        SortedMap sm = new TreeMap();
        for (int i = 0; i < configs.length; i++) {
            sm.put(configs[i].getPid(), configs[i]);
            String fpid = configs[i].getFactoryPid();
            if (null != fpid) {
                factories.add(fpid);
            }
        }

        for (Iterator mi = sm.values().iterator(); mi.hasNext();) {
            Configuration config = (Configuration) mi.next();
            pw.println("<configuration>");

            // Emette una ad una le proprieta' della configurazione
            Dictionary props = config.getProperties();
            if (props != null) {
                SortedSet keys = new TreeSet();
                for (Enumeration ke = props.keys(); ke.hasMoreElements();)
                    keys.add(ke.nextElement());
                for (Iterator ki = keys.iterator(); ki.hasNext();) {
                    String key = (String) ki.next();

                    pw.print("<property type=\"" + props.get(key).getClass().getSimpleName() + "\" name=\""
                            + key + "\">");

                    if (props.get(key).getClass().isArray() == true) {
                        pw.println();
                        Object value = props.get(key);
                        int len = Array.getLength(value);
                        for (int i = 0; i < len; i++) {
                            Object element = Array.get(value, i);
                            pw.print("<item>" + element.toString() + "</item>");
                        }
                    } else
                        pw.print(props.get(key));

                    pw.println("</property>");
                }
            }
            pw.println("</configuration>");
        }
    }
    pw.println("</configurations>");
    pw.flush();
}

From source file:com.espertech.esper.client.scopetest.EPAssertionUtil.java

/**
 * For a given array, copy the array elements into a new array of Object[] type.
 * @param array input array/*from  www.  j a  v  a  2s  .c o  m*/
 * @return object array
 */
public static Object[] toObjectArray(Object array) {
    if ((array == null) || (!array.getClass().isArray())) {
        throw new IllegalArgumentException(
                "Object not an array but type '" + (array == null ? "null" : array.getClass()) + "'");
    }
    int size = Array.getLength(array);
    Object[] val = new Object[size];
    for (int i = 0; i < size; i++) {
        val[i] = Array.get(array, i);
    }
    return val;
}

From source file:org.apache.marmotta.platform.core.services.config.ConfigurationServiceImpl.java

/**
 * Try figuring out on which port the server is running ...
 *//*from  ww  w  .j a va 2 s .c  o m*/
@Override
public int getServerPort() {

    if (serverPort == 0) {

        if (isTomcat6()) {
            // tomcat <= 6.x
            try {
                Object server = Class.forName("org.apache.catalina.ServerFactory").getMethod("getServer")
                        .invoke(null);
                Object service = Array.get(server.getClass().getMethod("findServices").invoke(server), 0);
                Object connector = Array.get(service.getClass().getMethod("findConnectors").invoke(service), 0);

                int port = (Integer) connector.getClass().getMethod("getPort").invoke(connector);
                log.info("Tomcat <= 6.x detected, server port: {}", port);
                serverPort = port;
            } catch (Exception e) {
            }
        } else if (isTomcat7()) {
            // tomcat 7.x
            try {
                MBeanServer mBeanServer = MBeanServerFactory.findMBeanServer(null).get(0);
                ObjectName name = new ObjectName("Catalina", "type", "Server");
                Object server = mBeanServer.getAttribute(name, "managedResource");

                Object service = Array.get(server.getClass().getMethod("findServices").invoke(server), 0);
                Object connector = Array.get(service.getClass().getMethod("findConnectors").invoke(service), 0);

                int port = (Integer) connector.getClass().getMethod("getPort").invoke(connector);
                log.info("Tomcat 7.x detected, server port: {}", port);
                serverPort = port;
            } catch (Exception e) {
            }
        } else {

            log.warn("not running on Tomcat, could not determine server port, returning default of 8080");
            serverPort = 8080;
        }
    }

    return serverPort;

}