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:org.apache.axis.encoding.ser.ArraySerializer.java

/**
 * Serialize an element that is an array.
 * @param name is the element name// w  w w  .j  a  va 2s. c  om
 * @param attributes are the attributes...serialize is free to add more.
 * @param value is the value
 * @param context is the SerializationContext
 */
public void serialize(QName name, Attributes attributes, Object value, SerializationContext context)
        throws IOException {
    if (value == null)
        throw new IOException(Messages.getMessage("cantDoNullArray00"));

    MessageContext msgContext = context.getMessageContext();
    SchemaVersion schema = SchemaVersion.SCHEMA_2001;
    SOAPConstants soap = SOAPConstants.SOAP11_CONSTANTS;
    boolean encoded = context.isEncoded();

    if (msgContext != null) {
        schema = msgContext.getSchemaVersion();
        soap = msgContext.getSOAPConstants();
    }

    Class cls = value.getClass();
    Collection list = null;

    if (!cls.isArray()) {
        if (!(value instanceof Collection)) {
            throw new IOException(Messages.getMessage("cantSerialize00", cls.getName()));
        }
        list = (Collection) value;
    }

    // Get the componentType of the array/list
    Class componentClass;
    if (list == null) {
        componentClass = cls.getComponentType();
    } else {
        componentClass = Object.class;
    }

    // Get the QName of the componentType
    // if it wasn't passed in from the constructor
    QName componentTypeQName = this.componentType;

    // Check to see if componentType is also an array.
    // If so, set the componentType to the most nested non-array
    // componentType.  Increase the dims string by "[]"
    // each time through the loop.
    // Note from Rich Scheuerle:
    //    This won't handle Lists of Lists or
    //    arrays of Lists....only arrays of arrays.
    String dims = "";

    if (componentTypeQName != null) {
        // if we have a Type QName at this point,
        // this is because ArraySerializer has been instanciated with it
        TypeMapping tm = context.getTypeMapping();
        SerializerFactory factory = (SerializerFactory) tm.getSerializer(componentClass, componentTypeQName);
        while (componentClass.isArray() && factory instanceof ArraySerializerFactory) {
            ArraySerializerFactory asf = (ArraySerializerFactory) factory;
            componentClass = componentClass.getComponentType();
            QName componentType = null;
            if (asf.getComponentType() != null) {
                componentType = asf.getComponentType();
                if (encoded) {
                    componentTypeQName = componentType;
                }
            }
            // update factory with the new values
            factory = (SerializerFactory) tm.getSerializer(componentClass, componentType);
            if (soap == SOAPConstants.SOAP12_CONSTANTS)
                dims += "* ";
            else
                dims += "[]";
        }
    } else {
        // compatibility mode
        while (componentClass.isArray()) {
            componentClass = componentClass.getComponentType();
            if (soap == SOAPConstants.SOAP12_CONSTANTS)
                dims += "* ";
            else
                dims += "[]";
        }
    }

    // Try the current XML type from the context
    if (componentTypeQName == null) {
        componentTypeQName = context.getCurrentXMLType();
        if (componentTypeQName != null) {
            if ((componentTypeQName.equals(xmlType) || componentTypeQName.equals(Constants.XSD_ANYTYPE)
                    || componentTypeQName.equals(soap.getArrayType()))) {
                componentTypeQName = null;
            }
        }
    }

    if (componentTypeQName == null) {
        componentTypeQName = context.getItemType();
    }

    // Then check the type mapping for the class
    if (componentTypeQName == null) {
        componentTypeQName = context.getQNameForClass(componentClass);
    }

    // If still not found, look at the super classes
    if (componentTypeQName == null) {
        Class searchCls = componentClass;
        while (searchCls != null && componentTypeQName == null) {
            searchCls = searchCls.getSuperclass();
            componentTypeQName = context.getQNameForClass(searchCls);
        }
        if (componentTypeQName != null) {
            componentClass = searchCls;
        }
    }

    // Still can't find it?  Throw an error.
    if (componentTypeQName == null) {
        throw new IOException(Messages.getMessage("noType00", componentClass.getName()));
    }

    int len = (list == null) ? Array.getLength(value) : list.size();
    String arrayType = "";
    int dim2Len = -1;
    if (encoded) {
        if (soap == SOAPConstants.SOAP12_CONSTANTS) {
            arrayType = dims + len;
        } else {
            arrayType = dims + "[" + len + "]";
        }

        // Discover whether array can be serialized directly as a two-dimensional
        // array (i.e. arrayType=int[2,3]) versus an array of arrays.
        // Benefits:
        //   - Less text passed on the wire.
        //   - Easier to read wire format
        //   - Tests the deserialization of multi-dimensional arrays.
        // Drawbacks:
        //   - Is not safe!  It is possible that the arrays are multiply
        //     referenced.  Transforming into a 2-dim array will cause the
        //     multi-referenced information to be lost.  Plus there is no
        //     way to determine whether the arrays are multi-referenced.
        //   - .NET currently (Dec 2002) does not support 2D SOAP-encoded arrays
        //
        // OLD Comment as to why this was ENABLED:
        // It is necessary for
        // interoperability (echo2DStringArray).  It is 'safe' for now
        // because Axis treats arrays as non multi-ref (see the note
        // in SerializationContext.isPrimitive(...) )
        // More complicated processing is necessary for 3-dim arrays, etc.
        //
        // Axis 1.1 - December 2002
        // Turned this OFF because Microsoft .NET can not deserialize
        // multi-dimensional SOAP-encoded arrays, and this interopability
        // is pretty high visibility. Make it a global configuration parameter:
        //  <parameter name="enable2DArrayEncoding" value="true"/>    (tomj)
        //

        // Check the message context to see if we should turn 2D processing ON
        // Default is OFF
        boolean enable2Dim = false;

        // Vidyanand : added this check
        if (msgContext != null) {
            enable2Dim = JavaUtils
                    .isTrueExplicitly(msgContext.getProperty(AxisEngine.PROP_TWOD_ARRAY_ENCODING));
        }

        if (enable2Dim && !dims.equals("")) {
            if (cls.isArray() && len > 0) {
                boolean okay = true;
                // Make sure all of the component arrays are the same size
                for (int i = 0; i < len && okay; i++) {

                    Object elementValue = Array.get(value, i);
                    if (elementValue == null)
                        okay = false;
                    else if (dim2Len < 0) {
                        dim2Len = Array.getLength(elementValue);
                        if (dim2Len <= 0) {
                            okay = false;
                        }
                    } else if (dim2Len != Array.getLength(elementValue)) {
                        okay = false;
                    }
                }
                // Update the arrayType to use mult-dim array encoding
                if (okay) {
                    dims = dims.substring(0, dims.length() - 2);
                    if (soap == SOAPConstants.SOAP12_CONSTANTS)
                        arrayType = dims + len + " " + dim2Len;
                    else
                        arrayType = dims + "[" + len + "," + dim2Len + "]";
                } else {
                    dim2Len = -1;
                }
            }
        }
    }

    // Need to distinguish if this is array processing for an
    // actual schema array or for a maxOccurs usage.
    // For the maxOccurs case, the currentXMLType of the context is
    // the same as the componentTypeQName.
    QName itemQName = context.getItemQName();
    boolean maxOccursUsage = !encoded && itemQName == null
            && componentTypeQName.equals(context.getCurrentXMLType());

    if (encoded) {
        AttributesImpl attrs;
        if (attributes == null) {
            attrs = new AttributesImpl();
        } else if (attributes instanceof AttributesImpl) {
            attrs = (AttributesImpl) attributes;
        } else {
            attrs = new AttributesImpl(attributes);
        }

        String compType = context.attributeQName2String(componentTypeQName);

        if (attrs.getIndex(soap.getEncodingURI(), soap.getAttrItemType()) == -1) {
            String encprefix = context.getPrefixForURI(soap.getEncodingURI());

            if (soap != SOAPConstants.SOAP12_CONSTANTS) {
                compType = compType + arrayType;

                attrs.addAttribute(soap.getEncodingURI(), soap.getAttrItemType(), encprefix + ":arrayType",
                        "CDATA", compType);

            } else {
                attrs.addAttribute(soap.getEncodingURI(), soap.getAttrItemType(), encprefix + ":itemType",
                        "CDATA", compType);

                attrs.addAttribute(soap.getEncodingURI(), "arraySize", encprefix + ":arraySize", "CDATA",
                        arrayType);
            }
        }

        // Force type to be SOAP_ARRAY for all array serialization.
        //
        // There are two choices here:
        // Force the type to type=SOAP_ARRAY
        //   Pros:  More interop test successes.
        //   Cons:  Since we have specific type information it
        //          is more correct to use it.  Plus the specific
        //          type information may be important on the
        //          server side to disambiguate overloaded operations.
        // Use the specific type information:
        //   Pros:  The specific type information is more correct
        //          and may be useful for operation overloading.
        //   Cons:  More interop test failures (as of 2/6/2002).
        //
        String qname = context.getPrefixForURI(schema.getXsiURI(), "xsi") + ":type";
        QName soapArray;
        if (soap == SOAPConstants.SOAP12_CONSTANTS) {
            soapArray = Constants.SOAP_ARRAY12;
        } else {
            soapArray = Constants.SOAP_ARRAY;
        }

        int typeI = attrs.getIndex(schema.getXsiURI(), "type");
        if (typeI != -1) {
            attrs.setAttribute(typeI, schema.getXsiURI(), "type", qname, "CDATA",
                    context.qName2String(soapArray));
        } else {
            attrs.addAttribute(schema.getXsiURI(), "type", qname, "CDATA", context.qName2String(soapArray));
        }

        attributes = attrs;
    }

    // For the maxOccurs case, each item is named with the QName
    // we got in the arguments.  For normal array case, we write an element with
    // that QName, and then serialize each item as <item>
    QName elementName = name;
    Attributes serializeAttr = attributes;
    if (!maxOccursUsage) {
        serializeAttr = null; // since we are putting them here
        context.startElement(name, attributes);
        if (itemQName != null)
            elementName = itemQName;
        else if (componentQName != null)
            elementName = componentQName;
    }

    if (dim2Len < 0) {
        // Normal case, serialize each array element
        if (list == null) {
            for (int index = 0; index < len; index++) {
                Object aValue = Array.get(value, index);

                // Serialize the element.
                context.serialize(elementName,
                        (serializeAttr == null ? serializeAttr : new AttributesImpl(serializeAttr)), aValue,
                        componentTypeQName, componentClass); // prefered type QName
            }
        } else {
            for (Iterator iterator = list.iterator(); iterator.hasNext();) {
                Object aValue = iterator.next();

                // Serialize the element.
                context.serialize(elementName,
                        (serializeAttr == null ? serializeAttr : new AttributesImpl(serializeAttr)), aValue,
                        componentTypeQName, componentClass); // prefered type QName
            }
        }
    } else {
        // Serialize as a 2 dimensional array
        for (int index = 0; index < len; index++) {
            for (int index2 = 0; index2 < dim2Len; index2++) {
                Object aValue = Array.get(Array.get(value, index), index2);
                context.serialize(elementName, null, aValue, componentTypeQName, componentClass);
            }
        }
    }

    if (!maxOccursUsage)
        context.endElement();
}

From source file:org.jdesigner.platform.web.converter.ArrayConverter.java

/**
 * Handles conversion to a String.//  ww w.j  a  va 2 s .c o m
 * 
 * @param value
 *            The value to be converted.
 * @return the converted String value.
 * @throws Throwable
 *             if an error occurs converting to a String
 */
protected String convertToString(Object value) throws Throwable {

    int size = 0;
    Iterator iterator = null;
    Class type = value.getClass();
    if (type.isArray()) {
        size = Array.getLength(value);
    } else {
        Collection collection = convertToCollection(type, value);
        size = collection.size();
        iterator = collection.iterator();
    }

    if (size == 0) {
        return (String) getDefault(String.class);
    }

    if (onlyFirstToString) {
        size = 1;
    }

    // Create a StringBuffer containing a delimited list of the values
    StringBuffer buffer = new StringBuffer();
    for (int i = 0; i < size; i++) {
        if (i > 0) {
            buffer.append(delimiter);
        }
        Object element = iterator == null ? Array.get(value, i) : iterator.next();
        element = elementConverter.convert(String.class, element);
        if (element != null) {
            buffer.append(element);
        }
    }

    return buffer.toString();

}

From source file:com.wavemaker.json.JSONMarshaller.java

/**
 * doMarshal() returns some status Objects.
 * //w  w w .j a v  a 2 s .  c o m
 * CYCLE_DETECTED_OBJECT will be returned if a cycle was detected at a lower level, and this level needs to be not
 * written.
 * 
 * fieldDefinition should never be null; its enclosed typeDefinition may very well be null.
 */
protected static Object doMarshal(Writer writer, Object obj, Object root, JSONState js, boolean sort,
        boolean topLevel, Stack<Object> touchedObjects, Stack<String> propertyNames,
        FieldDefinition fieldDefinition, int arrayLevel, TypeState typeState, boolean prettyPrint, int level,
        Logger logger) throws IOException {

    if (fieldDefinition == null) {
        throw new NullArgumentException("fieldDefinition");
    }

    touchedObjects.push(obj);
    try {
        if (obj != null && fieldDefinition.getTypeDefinition() == null) {
            fieldDefinition = ReflectTypeUtils.getFieldDefinition(obj.getClass(), typeState, false, null);
            arrayLevel = 0;
        }

        // do value conversion
        if (js.getValueTransformer() != null) {
            Tuple.Three<Object, FieldDefinition, Integer> tuple = js.getValueTransformer().transformToJSON(obj,
                    fieldDefinition, arrayLevel, root, getPropertyName(propertyNames, js), js.getTypeState());
            if (tuple != null) {
                obj = tuple.v1;
                fieldDefinition = tuple.v2;
                arrayLevel = tuple.v3;
            }
        }

        if (arrayLevel == fieldDefinition.getDimensions() && fieldDefinition.getTypeDefinition() != null
                && fieldDefinition.getTypeDefinition() instanceof WriteObjectConverter) {
            ((WriteObjectConverter) fieldDefinition.getTypeDefinition()).writeObject(obj, root,
                    getPropertyName(propertyNames, js), writer);
        } else if (obj == null) {
            writer.write("null");

            // handle arrays & Collections
        } else if (arrayLevel < fieldDefinition.getDimensions() || obj.getClass().isArray()) {

            writer.write("[");
            boolean firstElement = true;

            if (obj instanceof Collection) {
                for (Object elem : (Collection<?>) obj) {
                    if (!firstElement) {
                        writer.write(",");

                        if (prettyPrint) {
                            writer.write(" ");
                        }
                    }

                    doMarshal(writer, elem, root, js, sort, false, touchedObjects, propertyNames,
                            fieldDefinition, arrayLevel + 1, typeState, prettyPrint, level, logger);

                    if (firstElement) {
                        firstElement = false;
                    }
                }
            } else if (obj.getClass().isArray()) {
                int length = Array.getLength(obj);
                Object elem;

                for (int i = 0; i < length; i++) {
                    elem = Array.get(obj, i);

                    if (!firstElement) {
                        writer.write(",");

                        if (prettyPrint) {
                            writer.write(" ");
                        }
                    }

                    doMarshal(writer, elem, root, js, sort, false, touchedObjects, propertyNames,
                            fieldDefinition, arrayLevel + 1, typeState, prettyPrint, level, logger);
                    if (firstElement) {
                        firstElement = false;
                    }
                }
            } else {
                throw new WMRuntimeException(MessageResource.JSON_UNKNOWN_COLL_OR_ARRAY, obj, obj.getClass());
            }

            writer.write("]");
            // check for primitives
        } else if (fieldDefinition.getTypeDefinition() != null
                && fieldDefinition.getTypeDefinition() instanceof PrimitiveTypeDefinition) {
            ((PrimitiveTypeDefinition) fieldDefinition.getTypeDefinition()).toJson(writer, obj);
            // handle maps & objects
        } else {
            handleObject(obj, root, js, writer, touchedObjects, propertyNames, sort, fieldDefinition,
                    arrayLevel, typeState, prettyPrint, level, logger);
        }

        return null;
    } finally {
        touchedObjects.pop();
    }
}

From source file:org.archive.crawler.restlet.JobRelatedResource.java

/**
 * Constructs a nested Map data structure of the information represented
 * by {@code object}. The result is particularly suitable for use with with
 * {@link XmlMarshaller}.//from   w ww . java  2  s .  c  o m
 * 
 * @param field
 *            field name for object
 * @param object
 *            object to make presentable map for
 * @param alreadyWritten
 *            Set of objects already made presentable whose addition to the
 *            Map should be suppressed
 * @param beanPathPrefix
 *            beanPath prefix to apply to sub fields browse links
 * @return the presentable Map
 */
protected Map<String, Object> makePresentableMapFor(String field, Object object, HashSet<Object> alreadyWritten,
        String beanPathPrefix) {
    Map<String, Object> info = new LinkedHashMap<String, Object>();
    Reference baseRef = getRequest().getResourceRef().getBaseRef();

    String beanPath = beanPathPrefix;

    if (StringUtils.isNotBlank(field)) {
        info.put("field", field);

        if (StringUtils.isNotBlank(beanPathPrefix)) {
            if (beanPathPrefix.endsWith(".")) {
                beanPath += field;
            } else if (beanPathPrefix.endsWith("[")) {
                beanPath += field + "]";
            }
            info.put("url", new Reference(baseRef, "../beans/" + TextUtils.urlEscape(beanPath)).getTargetRef());
        }
    }
    String key = getBeanToNameMap().get(object);

    if (object == null) {
        info.put("propValue", null);
        return info;
    }
    if (object instanceof String || BeanUtils.isSimpleValueType(object.getClass()) || object instanceof File) {
        info.put("class", object.getClass().getName());
        info.put("propValue", object);
        return info;
    }
    if (alreadyWritten.contains(object)) {
        info.put("propValuePreviouslyDescribed", true);
        return info;
    }

    alreadyWritten.add(object); // guard against repeats and cycles

    if (StringUtils.isNotBlank(key) && StringUtils.isNotBlank(field)) {
        info.put("key", key);
        info.put("url", new Reference(baseRef, "../beans/" + key).getTargetRef());
        return info;
    }

    info.put("class", object.getClass().getName());

    Collection<Object> properties = new LinkedList<Object>();
    BeanWrapperImpl bwrap = new BeanWrapperImpl(object);
    for (PropertyDescriptor pd : getPropertyDescriptors(bwrap)) {

        if (pd.getReadMethod() != null && !pd.isHidden()) {
            String propName = pd.getName();
            if (beanPath != null) {
                beanPathPrefix = beanPath + ".";
            }
            Object propValue = makePresentableMapFor(propName, bwrap.getPropertyValue(propName), alreadyWritten,
                    beanPathPrefix);
            properties.add(propValue);
        }
    }
    if (properties.size() > 0) {
        info.put("properties", properties);
    }

    Collection<Object> propValues = new LinkedList<Object>();
    if (object.getClass().isArray()) {
        // TODO: may want a special handling for an array of
        // primitive types?
        int len = Array.getLength(object);
        for (int i = 0; i < len; i++) {
            if (beanPath != null) {
                beanPathPrefix = beanPath + "[";
            }
            // TODO: protect against overlong content? 
            propValues.add(makePresentableMapFor(i + "", Array.get(object, i), alreadyWritten, beanPathPrefix));
        }
    }
    if (object instanceof List<?>) {
        List<?> list = (List<?>) object;
        for (int i = 0; i < list.size(); i++) {
            if (beanPath != null) {
                beanPathPrefix = beanPath + "[";
            }
            // TODO: protect against overlong content?
            try {
                propValues.add(makePresentableMapFor(i + "", list.get(i), alreadyWritten, beanPathPrefix));
            } catch (Exception e) {
                LOGGER.warning(list + ".get(" + i + ") -" + e);
            }
        }
    } else if (object instanceof Iterable<?>) {
        for (Object next : (Iterable<?>) object) {
            propValues.add(makePresentableMapFor("#", next, alreadyWritten, beanPathPrefix));
        }
    }
    if (object instanceof Map<?, ?>) {
        for (Object next : ((Map<?, ?>) object).entrySet()) {
            // TODO: protect against giant maps?
            Map.Entry<?, ?> entry = (Map.Entry<?, ?>) next;
            if (beanPath != null) {
                beanPathPrefix = beanPath + "[";
            }
            propValues.add(makePresentableMapFor(entry.getKey().toString(), entry.getValue(), alreadyWritten,
                    beanPathPrefix));
        }
    }
    if (propValues.size() > 0) {
        info.put("propValue", propValues);
    }

    return info;
}

From source file:com.dnw.json.J.java

/**
 * Appends the given array to the string buffer.
 * //from   w w  w . j  av a2s  .c o m
 * @author manbaum
 * @since Oct 11, 2014
 * @param sb the string buffer.
 * @param array the array to append.
 */
private final static void emitArray(final StringBuffer sb, final Object array) {
    sb.append('[');
    int length = Array.getLength(array);
    for (int i = 0; i < length; i++) {
        if (i > 0) {
            sb.append(',');
        }
        J.emit(sb, Array.get(array, i));
    }
    sb.append(']');
}

From source file:org.istsms.util.Javabean2JSON.java

private static JSONArray _toJSONArray(Object value, Class c) {
    if (value == null)
        return null;
    if (!c.isArray())
        return null;
    if (value.getClass().isArray()) {
        //it's an array!                  
        Vector v = new Vector();
        int length = Array.getLength(value);
        for (int j = 0; j < length; j++) {
            Object element = Array.get(value, j);
            if (element != null) {
                if (element.getClass().isArray()) {
                    v.add(_toJSONArray(element, c.getComponentType()));
                } else {
                    String suggestedComponentType = c.getComponentType().getCanonicalName();
                    if (isCalendar(element.getClass().getCanonicalName())) {
                        v.add(fromJavaCalendar((java.util.Calendar) element));
                    } else if (isPrimitive(element.getClass().getCanonicalName())) {
                        v.add(equalPrimitive(element.getClass().getCanonicalName(), suggestedComponentType)
                                ? element.toString()
                                //                            (element instanceof java.util.Calendar)
                                //                               ?""+((java.util.Calendar)element).getTime().getTime()   
                                //                            :element.toString()

                                : toJSONObject(element));
                    } else {
                        v.add(suggestedComponentType.equals(element.getClass().getCanonicalName())
                                ? _toJSONObject(element)
                                : toJSONObject(element));
                    }/*  w w w .  j a  va2  s . c o  m*/
                }
            } else {
                v.add(JSONObject.NULL);
            }
        }
        return new JSONArray(v);
    }
    return null;
}

From source file:org.dcm4chee.archive.conf.DeepEquals.java

/**
 * Deeply compare to Arrays []. Both arrays must be of the same type, same length, and all
 * elements within the arrays must be deeply equal in order to return true.
 * @param array1 [] type (Object[], String[], etc.)
 * @param array2 [] type (Object[], String[], etc.)
 * @param stack add items to compare to the Stack (Stack versus recursion)
 * @param visited Set of objects already compared (prevents cycles)
 * @return true if the two arrays are the same length and contain deeply equivalent items.
 *///from  ww w.j a  v a 2  s  .c  om
private static boolean compareArrays(Object array1, Object array2, LinkedList stack, Set visited) {
    // Same instance check already performed...

    int len = Array.getLength(array1);
    if (len != Array.getLength(array2)) {
        return false;
    }

    // try sorting

    if (len > 0) {
        if (Array.get(array1, 0) instanceof Comparable) {

            Class<?> c = Array.get(array1, 0).getClass();

            if (ClassUtils.isPrimitiveOrWrapper(c)) {
                /*   Arrays.sort(array1);
                     Arrays.sort((Object[]) array2);*/

            } else {

                Arrays.sort((Object[]) array1);
                Arrays.sort((Object[]) array2);
            }

        }
    }

    for (int i = 0; i < len; i++) {
        DualKey dk = new DualKey(Array.get(array1, i), Array.get(array2, i));
        if (!visited.contains(dk)) { // push contents for further comparison
            stack.addFirst(dk);
        }
    }
    return true;
}

From source file:org.inwiss.platform.common.util.ConvertUtil.java

/**
 * Converts primitive array to array of objects. Each element in returned array will have run-time class
 * equivalent to its primitive type (e.g. <code>java.lang.Integer</code> is object equivalent to <code>int</code>,
 * <code>java.lang.Boolean</code> is object equivalent to <code>boolean</code>, etc.)
 *
 * @param primitiveArray Array of primitives which needs to be converted to objects
 * @return Array of object, each element is object equivalent to corresponding primitive value
 * @throws IllegalArgumentException if specified argument is not a primitive array
 *///from   w  w  w . ja v  a2 s .  co m
public static Object[] convertPrimitivesToObjects(Object primitiveArray) {
    if (primitiveArray == null) {
        return null;
    }

    if (!primitiveArray.getClass().isArray()) {
        throw new IllegalArgumentException("Specified object is not array");
    }

    if (primitiveArray instanceof Object[]) {
        throw new IllegalArgumentException("Specified object is not primitive array");
    }

    int length = Array.getLength(primitiveArray);
    Object[] result = new Object[length];
    for (int i = 0; i < length; i++) {
        result[i] = Array.get(primitiveArray, i);
    }

    return result;
}

From source file:org.codehaus.enunciate.modules.rest.RESTResourceExporter.java

/**
 * Handles a specific REST operation.// w ww .  j a v  a2 s . co m
 *
 * @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;
}

From source file:org.ebayopensource.common.util.DataUtil.java

public static List<String> getStringList(Object object) {
    if (object == null) {
        return null;
    }/*  w ww.j a  v  a2  s.c  om*/

    String[] result;
    if (object instanceof List) {
        List<String> orig = (List<String>) object;
        List<String> list = new ArrayList<>(orig.size());
        for (int i = 0; i < orig.size(); i++) {
            list.add(String.valueOf(orig.get(i)));
        }
        return list;
    } else if (object instanceof String[]) {
        result = (String[]) object;
        List<String> list = new ArrayList<>(result.length);
        Collections.addAll(list, result);
        return list;
    } else if (object instanceof String) {
        String str = (String) object;
        str = str.trim();

        result = StringUtils.split(str, ',');
        List<String> list = new ArrayList<>(result.length);
        Collections.addAll(list, result);
        return list;
    } else if (object instanceof Object[]) {
        Object[] array = (Object[]) object;
        List<String> list = new ArrayList<>(array.length);
        for (Object anArray : array) {
            list.add(getString(anArray, null));
        }
        return list;
    } else if (object.getClass().isArray()) {
        int len = Array.getLength(object);
        List<String> list = new ArrayList<>(len);
        for (int i = 0; i < len; i++) {
            list.add(getString(Array.get(object, i), null));
        }
        return list;
    } else if (object instanceof Number || object instanceof Boolean || object instanceof Character) {
        return Collections.singletonList(object.toString());
    } else {
        return null;
    }
}