Example usage for java.lang.reflect Array set

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

Introduction

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

Prototype

public static native void set(Object array, int index, Object value)
        throws IllegalArgumentException, ArrayIndexOutOfBoundsException;

Source Link

Document

Sets the value of the indexed component of the specified array object to the specified new value.

Usage

From source file:com.datos.vfs.util.DelegatingFileSystemOptionsBuilder.java

/**
 * tries to convert the value and pass it to the given method
 *//*ww w.j a v a 2s . c  o m*/
private boolean convertValuesAndInvoke(final Method configSetter, final Context ctx)
        throws FileSystemException {
    final Class<?>[] parameters = configSetter.getParameterTypes();
    if (parameters.length < 2) {
        return false;
    }
    if (!parameters[0].isAssignableFrom(FileSystemOptions.class)) {
        return false;
    }

    final Class<?> valueParameter = parameters[1];
    Class<?> type;
    if (valueParameter.isArray()) {
        type = valueParameter.getComponentType();
    } else {
        if (ctx.values.length > 1) {
            return false;
        }

        type = valueParameter;
    }

    if (type.isPrimitive()) {
        final Class<?> objectType = PRIMATIVE_TO_OBJECT.get(type.getName());
        if (objectType == null) {
            log.warn(Messages.getString("vfs.provider/config-unexpected-primitive.error", type.getName()));
            return false;
        }
        type = objectType;
    }

    final Class<? extends Object> valueClass = ctx.values[0].getClass();
    if (type.isAssignableFrom(valueClass)) {
        // can set value directly
        invokeSetter(valueParameter, ctx, configSetter, ctx.values);
        return true;
    }
    if (valueClass != String.class) {
        log.warn(Messages.getString("vfs.provider/config-unexpected-value-class.error", valueClass.getName(),
                ctx.scheme, ctx.name));
        return false;
    }

    final Object convertedValues = Array.newInstance(type, ctx.values.length);

    Constructor<?> valueConstructor;
    try {
        valueConstructor = type.getConstructor(STRING_PARAM);
    } catch (final NoSuchMethodException e) {
        valueConstructor = null;
    }
    if (valueConstructor != null) {
        // can convert using constructor
        for (int iterValues = 0; iterValues < ctx.values.length; iterValues++) {
            try {
                Array.set(convertedValues, iterValues,
                        valueConstructor.newInstance(new Object[] { ctx.values[iterValues] }));
            } catch (final InstantiationException e) {
                throw new FileSystemException(e);
            } catch (final IllegalAccessException e) {
                throw new FileSystemException(e);
            } catch (final InvocationTargetException e) {
                throw new FileSystemException(e);
            }
        }

        invokeSetter(valueParameter, ctx, configSetter, convertedValues);
        return true;
    }

    Method valueFactory;
    try {
        valueFactory = type.getMethod("valueOf", STRING_PARAM);
        if (!Modifier.isStatic(valueFactory.getModifiers())) {
            valueFactory = null;
        }
    } catch (final NoSuchMethodException e) {
        valueFactory = null;
    }

    if (valueFactory != null) {
        // can convert using factory method (valueOf)
        for (int iterValues = 0; iterValues < ctx.values.length; iterValues++) {
            try {
                Array.set(convertedValues, iterValues,
                        valueFactory.invoke(null, new Object[] { ctx.values[iterValues] }));
            } catch (final IllegalAccessException e) {
                throw new FileSystemException(e);
            } catch (final InvocationTargetException e) {
                throw new FileSystemException(e);
            }
        }

        invokeSetter(valueParameter, ctx, configSetter, convertedValues);
        return true;
    }

    return false;
}

From source file:org.jolokia.converter.object.StringToObjectConverter.java

private Object convertListToArray(Class pType, List pList) {
    Class valueType = pType.getComponentType();
    Object ret = Array.newInstance(valueType, pList.size());
    int i = 0;/*w ww .  ja  va2  s. c  om*/
    for (Object value : pList) {
        if (value == null) {
            if (!valueType.isPrimitive()) {
                Array.set(ret, i++, null);
            } else {
                throw new IllegalArgumentException(
                        "Cannot use a null value in an array of type " + valueType.getSimpleName());
            }
        } else {
            if (valueType.isAssignableFrom(value.getClass())) {
                // Can be set directly
                Array.set(ret, i++, value);
            } else {
                // Try to convert from string
                Array.set(ret, i++, convertFromString(valueType.getCanonicalName(), value.toString()));
            }
        }
    }
    return ret;
}

From source file:net.jofm.DefaultFixedMapper.java

private void fromPrimitiveFieldList(Object destinationObject, StringBuilder line,
        PrimitiveFieldListMetaData primitiveFieldListMetadata) throws Exception {
    PrimitiveFieldMetaData counterFieldMetaData = primitiveFieldListMetadata.getCounterFieldMetaData();
    int counterLength = counterFieldMetaData.getLength();

    String counterData = read(line, counterLength);

    int counter = (Integer) counterFieldMetaData.getFormatter().parse(counterData, int.class);

    PrimitiveFieldMetaData fieldMetaData = primitiveFieldListMetadata.getFieldMetaData();
    int fieldLength = fieldMetaData.getLength();

    Object array = Array.newInstance(primitiveFieldListMetadata.getComponentType(), counter);

    StringBuilder readData = new StringBuilder();
    for (int i = 0; i < counter; i++) {
        String fieldData = read(line, fieldLength);
        readData.append(fieldData);//  w  w w .  j a va2  s  . c  o m
        Array.set(array, i,
                fieldMetaData.getFormatter().parse(fieldData, primitiveFieldListMetadata.getComponentType()));
    }

    setProperty(destinationObject, primitiveFieldListMetadata.getField().getName(), readData.toString(), array,
            primitiveFieldListMetadata.isIgnored());
}

From source file:org.gridgain.grid.util.json.GridJsonDeserializer.java

/**
 * Deserializes {@link JSONArray} to Java array of given class.
 *
 * @param arr Array for deserialization.
 * @param cls Class of resulted array.//  w w w .j  a va2  s .  co m
 * @return Deserialized array.
 * @throws GridException Thrown if any error occurs while deserialization.
 */
@SuppressWarnings("unchecked")
private static Object buildArray(JSONArray arr, Class cls) throws GridException {
    assert arr != null;
    assert cls != null;

    cls = cls.getComponentType();

    List list = new ArrayList(arr.size());

    for (Object elem : arr)
        if (!isDescriptor(elem))
            list.add(elem);

    int size = list.size();

    Object res = Array.newInstance(cls, size);

    for (int i = 0; i < size; i++)
        Array.set(res, i, deserialize(list.get(i), cls));

    return res;
}

From source file:org.enerj.apache.commons.beanutils.locale.LocaleConvertUtilsBean.java

/**
 * Convert an array of specified values to an array of objects of the
 * specified class (if possible) using the convertion pattern.
 *
 * @param values Value to be converted (may be null)
 * @param clazz Java array or element class to be converted to
 * @param locale The locale/* ww w  . j  ava 2  s  .c o  m*/
 * @param pattern The convertion pattern
 *
 * @exception ConversionException if thrown by an underlying Converter
 */
public Object convert(String values[], Class clazz, Locale locale, String pattern) {

    Class type = clazz;
    if (clazz.isArray()) {
        type = clazz.getComponentType();
    }
    if (log.isDebugEnabled()) {
        log.debug("Convert String[" + values.length + "] to class " + type.getName() + "[] using "
                + locale.toString() + " locale and " + pattern + " pattern");
    }

    Object array = Array.newInstance(type, values.length);
    for (int i = 0; i < values.length; i++) {
        Array.set(array, i, convert(values[i], type, locale, pattern));
    }

    return (array);
}

From source file:com.doitnext.http.router.DefaultInvoker.java

private void mapQueryParameter(QueryParameter parameterAnnotation, Object[] arguments, Class<?> parameterClass,
        Map<String, String[]> queryArgs, int paramIndex) throws TypeConversionException {
    String queryArg[] = queryArgs.get(parameterAnnotation.name());
    if (queryArg == null)
        return;/* w w w . j  a v a  2 s  .co m*/
    if (!parameterClass.isArray()) {
        if (queryArg.length > 0) {
            arguments[paramIndex] = stringConverter.convert(queryArg[0], parameterClass);
        }
    } else {
        Object queryParam = Array.newInstance(parameterClass.getComponentType(), queryArg.length);
        for (int x = 0; x < queryArg.length; x++) {
            Array.set(queryParam, x, stringConverter.convert(queryArg[x], parameterClass.getComponentType()));
        }
        arguments[paramIndex] = queryParam;
    }
}

From source file:com.icesoft.faces.renderkit.dom_html_basic.MenuRenderer.java

protected Object convertArray(FacesContext facesContext, UISelectMany uiSelectMany, Class componentType,
        String[] newSubmittedValues) throws ConverterException {

    // component type of String means no conversion is necessary
    if (componentType.equals(String.class)) {
        return newSubmittedValues;
    }//from www. j a v a2 s  .com

    // if newSubmittedValue is null return zero-length array
    if (newSubmittedValues == null) {
        return Array.newInstance(componentType, 0);
    }

    // create the array with specified component length
    int numberOfValues = newSubmittedValues.length;
    Object convertedValues = Array.newInstance(componentType, numberOfValues);

    // Determine if a converter is explicitly registered with the component
    Converter converter = uiSelectMany.getConverter();
    if (converter == null) {
        // Determine if there is a default converter for the class
        converter = getConverterForClass(componentType);
    }
    if (converter == null) {
        // we don't need to convert base Object types
        if (componentType.equals(Object.class)) {
            return newSubmittedValues;
        } else {
            throw new ConverterException("Converter is null");
        }
    }

    for (int index = 0; index < numberOfValues; index++) {

        // convert the next element
        Object nextConvertedElement = converter.getAsObject(facesContext, uiSelectMany,
                newSubmittedValues[index]);

        if (!componentType.isPrimitive()) {
            Array.set(convertedValues, index, nextConvertedElement);
        } else if (componentType.equals(Boolean.TYPE)) {

            Array.setBoolean(convertedValues, index, ((Boolean) nextConvertedElement).booleanValue());

        } else if (componentType.equals(Integer.TYPE)) {

            Array.setInt(convertedValues, index, ((Integer) nextConvertedElement).intValue());

        } else if (componentType.equals(Long.TYPE)) {

            Array.setLong(convertedValues, index, ((Long) nextConvertedElement).longValue());

        } else if (componentType.equals(Short.TYPE)) {

            Array.setShort(convertedValues, index, ((Short) nextConvertedElement).shortValue());

        } else if (componentType.equals(Byte.TYPE)) {

            Array.setByte(convertedValues, index, ((Byte) nextConvertedElement).byteValue());

        } else if (componentType.equals(Float.TYPE)) {

            Array.setFloat(convertedValues, index, ((Float) nextConvertedElement).floatValue());

        } else if (componentType.equals(Double.TYPE)) {

            Array.setDouble(convertedValues, index, ((Double) nextConvertedElement).doubleValue());

        } else if (componentType.equals(Character.TYPE)) {

            Array.setChar(convertedValues, index, ((Character) nextConvertedElement).charValue());

        }
    }
    return convertedValues;
}

From source file:com.google.feedserver.util.BeanUtil.java

/**
 * @param propertyType// www .ja va  2s  .  c o  m
 * @param valueArray
 * @param index
 * @param valueObject
 * @throws IntrospectionException
 * @throws IllegalAccessException
 * @throws IllegalArgumentException 
 * @throws InvocationTargetException
 * @throws ParseException 
 */
private void fillBeanInArray(Class<?> propertyType, Object valueArray, int index, Object valueObject)
        throws IntrospectionException, IllegalAccessException, InvocationTargetException,
        IllegalArgumentException, ParseException {
    Object beanObject = createBeanObject(propertyType, valueObject);
    Array.set(valueArray, index, beanObject);
}

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 {//from   ww  w.  j  av  a 2  s  .c o  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:org.codehaus.enunciate.modules.rest.RESTResourceExporter.java

/**
 * Handles a specific REST operation.//from  w  ww  .  ja va 2  s  . c  om
 *
 * @param operation The operation.
 * @param handler   The handler for the operation.
 * @param request   The request.
 * @param response  The response.
 * @return The model and view.
 */
protected ModelAndView handleRESTOperation(RESTOperation operation, RESTRequestContentTypeHandler handler,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (!this.endpoints.containsKey(operation.getVerb())) {
        throw new MethodNotAllowedException("Method not allowed.");
    }

    if ((this.multipartRequestHandler != null) && (this.multipartRequestHandler.isMultipart(request))) {
        request = this.multipartRequestHandler.handleMultipartRequest(request);
    }

    String requestContext = request.getRequestURI().substring(request.getContextPath().length());
    Map<String, String> contextParameters;
    try {
        contextParameters = resource.getContextParameterAndProperNounValues(requestContext);
    } catch (IllegalArgumentException e) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI());
        return null;
    }

    Object properNounValue = null;
    HashMap<String, Object> contextParameterValues = new HashMap<String, Object>();
    for (Map.Entry<String, String> entry : contextParameters.entrySet()) {
        String parameterName = entry.getKey();
        String parameterValue = entry.getValue();
        if (parameterName == null) {
            Class nounType = operation.getProperNounType();
            if (nounType != null) {
                //todo: provide a hook to some other conversion mechanism?
                try {
                    properNounValue = converter.convert(parameterValue, nounType);
                } catch (Exception e) {
                    throw new ParameterConversionException(parameterValue);
                }
            }
        } else {
            Class contextParameterType = operation.getContextParameterTypes().get(parameterName);
            if (contextParameterType != null) {
                //todo: provide a hook to some other conversion mechanism?
                try {
                    contextParameterValues.put(parameterName,
                            converter.convert(parameterValue, contextParameterType));
                } catch (Exception e) {
                    throw new ParameterConversionException(parameterValue);
                }
            }
        }
    }

    if ((properNounValue == null) && (operation.isProperNounOptional() != null)
            && (!operation.isProperNounOptional())) {
        throw new MissingParameterException(
                "A specific '" + resource.getNoun() + "' must be specified on the URL.");
    }

    HashMap<String, Object> adjectives = new HashMap<String, Object>();
    for (String adjective : operation.getAdjectiveTypes().keySet()) {
        Object adjectiveValue = null;

        if (!operation.getComplexAdjectives().contains(adjective)) {
            //not complex, map it.
            String[] parameterValues = request.getParameterValues(adjective);
            if ((parameterValues != null) && (parameterValues.length > 0)) {
                //todo: provide a hook to some other conversion mechanism?
                final Class adjectiveType = operation.getAdjectiveTypes().get(adjective);
                Class componentType = adjectiveType.isArray() ? adjectiveType.getComponentType()
                        : adjectiveType;
                Object adjectiveValues = Array.newInstance(componentType, parameterValues.length);
                for (int i = 0; i < parameterValues.length; i++) {
                    try {
                        Array.set(adjectiveValues, i, converter.convert(parameterValues[i], componentType));
                    } catch (Exception e) {
                        throw new KeyParameterConversionException(adjective, parameterValues[i]);
                    }
                }

                if (adjectiveType.isArray()) {
                    adjectiveValue = adjectiveValues;
                } else {
                    adjectiveValue = Array.get(adjectiveValues, 0);
                }
            }

            if ((adjectiveValue == null) && (!operation.getAdjectivesOptional().get(adjective))) {
                throw new MissingParameterException("Missing request parameter: " + adjective);
            }
        } else {
            //use spring's binding to map the complex adjective to the request parameters.
            try {
                adjectiveValue = operation.getAdjectiveTypes().get(adjective).newInstance();
            } catch (Throwable e) {
                throw new IllegalArgumentException(
                        "A complex adjective must have a simple, no-arg constructor. Invalid type: "
                                + operation.getAdjectiveTypes().get(adjective));
            }

            ServletRequestDataBinder binder = new ServletRequestDataBinder(adjectiveValue, adjective);
            binder.setIgnoreUnknownFields(true);
            binder.bind(request);
            BindException errors = binder.getErrors();
            if ((errors != null) && (errors.getAllErrors() != null) && (!errors.getAllErrors().isEmpty())) {
                ObjectError firstError = (ObjectError) errors.getAllErrors().get(0);
                String message = "Invalid parameter.";
                if (firstError instanceof FieldError) {
                    throw new ParameterConversionException(
                            ((FieldError) firstError).getRejectedValue().toString());
                }
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
            }
        }

        adjectives.put(adjective, adjectiveValue);
    }

    Object nounValue = null;
    if (operation.getNounValueType() != null) {
        Class nounValueType = operation.getNounValueType();
        if ((nounValueType.equals(DataHandler.class))
                || ((nounValueType.isArray() && nounValueType.getComponentType().equals(DataHandler.class)))) {
            Collection<DataHandler> dataHandlers;
            if (this.multipartRequestHandler != null) {
                dataHandlers = this.multipartRequestHandler.parseParts(request);
            } else {
                dataHandlers = new ArrayList<DataHandler>();
                dataHandlers.add(new DataHandler(
                        new RESTRequestDataSource(request, resource.getNounContext() + resource.getNoun())));
            }

            nounValue = dataHandlers;
            if (operation.getNounValueType().equals(DataHandler.class)) {
                nounValue = dataHandlers.iterator().next();
            } else if (mustConvertNounValueToArray(operation)) {
                Class type = operation.getNounValueType();
                if ((type.isArray() && type.getComponentType().equals(DataHandler.class))) {
                    nounValue = dataHandlers.toArray(new DataHandler[dataHandlers.size()]);
                }
            }
        } else {
            try {
                //if the operation has a noun value type, unmarshall it from the body....
                nounValue = handler.read(request);
            } catch (Exception e) {
                //if we can't unmarshal the noun value, continue if the noun value is optional.
                if (!operation.isNounValueOptional()) {
                    throw e;
                }
            }
        }
    }

    Object result = operation.invoke(properNounValue, contextParameterValues, adjectives, nounValue,
            this.endpoints.get(operation.getVerb()));

    //successful invocation, set up the response...
    if (result instanceof DataHandler) {
        response.setContentType(((DataHandler) result).getContentType());
        ((DataHandler) result).writeTo(response.getOutputStream());
    } else {
        response.setContentType(
                String.format("%s; charset=%s", operation.getContentType(), operation.getCharset()));
        handler.write(result, request, response);
    }
    return null;
}