Example usage for java.lang Class getComponentType

List of usage examples for java.lang Class getComponentType

Introduction

In this page you can find the example usage for java.lang Class getComponentType.

Prototype

public Class<?> getComponentType() 

Source Link

Document

Returns the Class representing the component type of an array.

Usage

From source file:com.jaspersoft.jasperserver.ws.axis2.scheduling.ReportJobBeanTraslator.java

protected Object toCollectionValue(Class parameterType, Object valueArray) {
    Object reportValue;/*w  ww  .jav  a 2  s  .  c o m*/
    int valueCount = Array.getLength(valueArray);
    if (parameterType.equals(Object.class) || parameterType.equals(Collection.class)
            || parameterType.equals(Set.class)) {
        Collection values = new ListOrderedSet();
        for (int i = 0; i < valueCount; ++i) {
            values.add(Array.get(valueArray, i));
        }
        reportValue = values;
    } else if (parameterType.equals(List.class)) {
        Collection values = new ArrayList(valueCount);
        for (int i = 0; i < valueCount; ++i) {
            values.add(Array.get(valueArray, i));
        }
        reportValue = values;
    } else if (parameterType.isArray()) {
        Class componentType = parameterType.getComponentType();
        if (componentType.equals(valueArray.getClass().getComponentType())) {
            reportValue = valueArray;
        } else {
            reportValue = Array.newInstance(componentType, valueCount);
            for (int i = 0; i < valueCount; ++i) {
                Array.set(reportValue, i, Array.get(valueArray, i));
            }
        }
    } else {
        throw new JSException("report.scheduling.ws.collection.parameter.type.not.supported",
                new Object[] { parameterType.getName() });
    }
    return reportValue;
}

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

/**
 *  Convert the specified value to the required type.
 *
 * @param type The Java type of target property
 * @param index The indexed subscript value (if any)
 * @param value The value to be converted
 *//*  w  ww .jav a2s  .  c  o m*/
protected Object convert(Class type, int index, Object value) {

    Object newValue = null;

    if (type.isArray() && (index < 0)) { // Scalar value into array
        if (value instanceof String) {
            String values[] = new String[1];
            values[0] = (String) value;
            newValue = ConvertUtils.convert((String[]) values, type);
        } else if (value instanceof String[]) {
            newValue = ConvertUtils.convert((String[]) value, type);
        } else {
            newValue = value;
        }
    } else if (type.isArray()) { // Indexed value into array
        if (value instanceof String) {
            newValue = ConvertUtils.convert((String) value, type.getComponentType());
        } else if (value instanceof String[]) {
            newValue = ConvertUtils.convert(((String[]) value)[0], type.getComponentType());
        } else {
            newValue = value;
        }
    } else { // Value into scalar
        if (value instanceof String) {
            newValue = ConvertUtils.convert((String) value, type);
        } else if (value instanceof String[]) {
            newValue = ConvertUtils.convert(((String[]) value)[0], type);
        } else {
            newValue = value;
        }
    }
    return newValue;
}

From source file:com.github.wshackle.java4cpp.J4CppMain.java

private static boolean isPrimitiveArray(Class clss) {
    return clss.isArray() && clss.getComponentType().isPrimitive();
}

From source file:org.apache.myfaces.shared_impl.renderkit.RendererUtils.java

/**
 * Find proper Converter for the entries in the associated List or Array of
 * the given UISelectMany as specified in API Doc of UISelectMany.
 *
 * @return the Converter or null if no Converter specified or needed
 * @throws FacesException if the Converter could not be created
 *//*from w  w  w  .  j  a  v  a  2s. co m*/
public static Converter findUISelectManyConverter(FacesContext facesContext, UISelectMany component) {
    Converter converter = component.getConverter();
    if (converter != null)
        return converter;

    //Try to find out by value binding
    ValueBinding vb = component.getValueBinding("value");
    if (vb == null)
        return null;

    Class valueType = vb.getType(facesContext);
    if (valueType == null)
        return null;

    if (List.class.isAssignableFrom(valueType)) {
        //According to API Doc of UISelectMany the assumed entry type for a List is String
        //--> so basically no converter needed

        // However, if the List contains something other than Strings, we can attempt
        // to find a suitable converter. In JDK 1.4, we can try to find out what the List
        // contains by looking at the SelectItem value of the first item. With generics in
        // JDK 1.5, it would be much easier to determine the type.

        List selectItems = RendererUtils.internalGetSelectItemList(component);

        if (selectItems != null && selectItems.size() > 0) {
            SelectItem selectItem = (SelectItem) selectItems.get(0);
            Class listComponentType = selectItem.getValue().getClass();

            if (!(String.class.equals(listComponentType))) {
                try {
                    return facesContext.getApplication().createConverter(listComponentType);
                } catch (FacesException e) {
                    log.error("No Converter for type " + listComponentType.getName() + " found", e);
                    return null;
                }
            }
        }

        return null;
    }

    if (!valueType.isArray()) {
        throw new IllegalArgumentException("ValueBinding for UISelectMany : " + getPathToComponent(component)
                + " must be of type List or Array");
    }

    Class arrayComponentType = valueType.getComponentType();
    if (String.class.equals(arrayComponentType))
        return null; //No converter needed for String type
    if (Object.class.equals(arrayComponentType))
        return null; //There is no converter for Object class

    try {
        return facesContext.getApplication().createConverter(arrayComponentType);
    } catch (FacesException e) {
        log.error("No Converter for type " + arrayComponentType.getName() + " found", e);
        return null;
    }
}

From source file:com.github.wshackle.java4cpp.J4CppMain.java

private static boolean isConstructorToMakeEasy(Constructor c, Class relClss) {
    Class<?> types[] = c.getParameterTypes();
    for (int i = 0; i < types.length; i++) {
        Class<?> type = types[i];
        if (type.isArray() && !type.getComponentType().isPrimitive()) {
            return false;
        }/* ww  w. j av a  2s  . c o m*/
    }
    for (int i = 0; i < types.length; i++) {
        Class<?> type = types[i];
        if (type.isArray() || isString(type)) {
            return true;
        }
    }
    return false;
    //        return Arrays.stream(c.getParameterTypes())
    //                .anyMatch(t -> t.isArray() || isString(t))
    //                && Arrays.stream(c.getParameterTypes())
    //                .noneMatch(t -> t.isArray() && !t.getComponentType().isPrimitive());
}

From source file:com.github.wshackle.java4cpp.J4CppMain.java

private static String classToParamName(Class<?> c) {
    if (c.isArray()) {
        return classToParamName(c.getComponentType()) + "Array";
    }/*from   w  w  w . j  a  va  2  s  .c o  m*/
    return c.getSimpleName().substring(0, 1).toLowerCase() + c.getSimpleName().substring(1);
}

From source file:com.github.wshackle.java4cpp.J4CppMain.java

private static boolean isMethodToMakeEasy(Method m) {
    if (Modifier.isStatic(m.getModifiers())) {
        return false;
    }//w w w.  j a v  a 2  s  .com
    Class<?> types[] = m.getParameterTypes();
    for (int i = 0; i < types.length; i++) {
        Class<?> type = types[i];
        if (type.isArray() && !type.getComponentType().isPrimitive()) {
            return false;
        }
    }
    for (int i = 0; i < types.length; i++) {
        Class<?> type = types[i];
        if (type.isArray() || isString(type)) {
            return true;
        }
    }
    return false;
    //        return !Modifier.isStatic(m.getModifiers())
    //                && Arrays.stream(m.getParameterTypes())
    //                .anyMatch(t -> t.isArray() || isString(t))
    //                && Arrays.stream(m.getParameterTypes())
    //                .noneMatch(t -> t.isArray() && !t.getComponentType().isPrimitive());
}

From source file:org.apache.hadoop.hbase.io.HbaseObjectWritable.java

/**
 * Read a {@link Writable}, {@link String}, primitive type, or an array of
 * the preceding.//w w w .  j  a  v  a2 s .co  m
 * @param in
 * @param objectWritable
 * @param conf
 * @return the object
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public static Object readObject(DataInput in, HbaseObjectWritable objectWritable, Configuration conf)
        throws IOException {
    Class<?> declaredClass = CODE_TO_CLASS.get(WritableUtils.readVInt(in));
    Object instance;
    if (declaredClass.isPrimitive()) { // primitive types
        if (declaredClass == Boolean.TYPE) { // boolean
            instance = Boolean.valueOf(in.readBoolean());
        } else if (declaredClass == Character.TYPE) { // char
            instance = Character.valueOf(in.readChar());
        } else if (declaredClass == Byte.TYPE) { // byte
            instance = Byte.valueOf(in.readByte());
        } else if (declaredClass == Short.TYPE) { // short
            instance = Short.valueOf(in.readShort());
        } else if (declaredClass == Integer.TYPE) { // int
            instance = Integer.valueOf(in.readInt());
        } else if (declaredClass == Long.TYPE) { // long
            instance = Long.valueOf(in.readLong());
        } else if (declaredClass == Float.TYPE) { // float
            instance = Float.valueOf(in.readFloat());
        } else if (declaredClass == Double.TYPE) { // double
            instance = Double.valueOf(in.readDouble());
        } else if (declaredClass == Void.TYPE) { // void
            instance = null;
        } else {
            throw new IllegalArgumentException("Not a primitive: " + declaredClass);
        }
    } else if (declaredClass.isArray()) { // array
        if (declaredClass.equals(byte[].class)) {
            instance = Bytes.readByteArray(in);
        } else if (declaredClass.equals(Result[].class)) {
            instance = Result.readArray(in);
        } else {
            int length = in.readInt();
            instance = Array.newInstance(declaredClass.getComponentType(), length);
            for (int i = 0; i < length; i++) {
                Array.set(instance, i, readObject(in, conf));
            }
        }
    } else if (declaredClass.equals(Array.class)) { //an array not declared in CLASS_TO_CODE
        Class<?> componentType = readClass(conf, in);
        int length = in.readInt();
        instance = Array.newInstance(componentType, length);
        for (int i = 0; i < length; i++) {
            Array.set(instance, i, readObject(in, conf));
        }
    } else if (List.class.isAssignableFrom(declaredClass)) { // List
        int length = in.readInt();
        instance = new ArrayList(length);
        for (int i = 0; i < length; i++) {
            ((ArrayList) instance).add(readObject(in, conf));
        }
    } else if (declaredClass == String.class) { // String
        instance = Text.readString(in);
    } else if (declaredClass.isEnum()) { // enum
        instance = Enum.valueOf((Class<? extends Enum>) declaredClass, Text.readString(in));
    } else if (declaredClass == Message.class) {
        String className = Text.readString(in);
        try {
            declaredClass = getClassByName(conf, className);
            instance = tryInstantiateProtobuf(declaredClass, in);
        } catch (ClassNotFoundException e) {
            LOG.error("Can't find class " + className, e);
            throw new IOException("Can't find class " + className, e);
        }
    } else { // Writable or Serializable
        Class instanceClass = null;
        int b = (byte) WritableUtils.readVInt(in);
        if (b == NOT_ENCODED) {
            String className = Text.readString(in);
            try {
                instanceClass = getClassByName(conf, className);
            } catch (ClassNotFoundException e) {
                LOG.error("Can't find class " + className, e);
                throw new IOException("Can't find class " + className, e);
            }
        } else {
            instanceClass = CODE_TO_CLASS.get(b);
        }
        if (Writable.class.isAssignableFrom(instanceClass)) {
            Writable writable = WritableFactories.newInstance(instanceClass, conf);
            try {
                writable.readFields(in);
            } catch (Exception e) {
                LOG.error("Error in readFields", e);
                throw new IOException("Error in readFields", e);
            }
            instance = writable;
            if (instanceClass == NullInstance.class) { // null
                declaredClass = ((NullInstance) instance).declaredClass;
                instance = null;
            }
        } else {
            int length = in.readInt();
            byte[] objectBytes = new byte[length];
            in.readFully(objectBytes);
            ByteArrayInputStream bis = null;
            ObjectInputStream ois = null;
            try {
                bis = new ByteArrayInputStream(objectBytes);
                ois = new ObjectInputStream(bis);
                instance = ois.readObject();
            } catch (ClassNotFoundException e) {
                LOG.error("Class not found when attempting to deserialize object", e);
                throw new IOException("Class not found when attempting to " + "deserialize object", e);
            } finally {
                if (bis != null)
                    bis.close();
                if (ois != null)
                    ois.close();
            }
        }
    }
    if (objectWritable != null) { // store values
        objectWritable.declaredClass = declaredClass;
        objectWritable.instance = instance;
    }
    return instance;
}

From source file:com.github.wshackle.java4cpp.J4CppMain.java

private static boolean checkClass(Class<?> clss, List<Class> classes) {
    Class<?> componentClass = clss.getComponentType();
    boolean ret = isString(clss)
            || clss.equals(Object.class) || clss.isPrimitive() || (clss.isArray() && null != componentClass
                    && !componentClass.isArray() && checkClass(componentClass, classes))
            || classes.contains(clss);//w ww .  j  a v a2s  . com
    if (!ret) {
        if (verbose) {
            if (clss.isArray()) {
                System.out.println("checkClass skipping " + clss + " component " + clss.getComponentType());
            } else {
                System.out.println("checkClass skipping " + clss);
            }
        }
    }
    return ret;
}

From source file:flex.messaging.services.http.proxy.RequestFilter.java

/**
 * Send the request.//from  ww w. java  2  s . co m
 *
 * @param context the context
 */
protected void sendRequest(ProxyContext context) {
    Target target = context.getTarget();
    String method = context.getMethod();
    HttpMethod httpMethod = context.getHttpMethod();
    final String BEGIN = "-- Begin ";
    final String END = "-- End ";
    final String REQUEST = " request --";

    if (httpMethod instanceof EntityEnclosingMethod) {
        Object data = processBody(context);
        Class dataClass = data.getClass();
        if (data instanceof String) {
            String requestString = (String) data;
            if (Log.isInfo()) {
                Logger logger = Log.getLogger(HTTPProxyService.LOG_CATEGORY);
                logger.debug(BEGIN + method + REQUEST);
                logger.debug(StringUtils.prettifyString(requestString));
                logger.debug(END + method + REQUEST);
            }

            try {
                StringRequestEntity requestEntity = new StringRequestEntity(requestString, null, "UTF-8");
                ((EntityEnclosingMethod) httpMethod).setRequestEntity(requestEntity);
            } catch (UnsupportedEncodingException ex) {
                ProxyException pe = new ProxyException(CAUGHT_ERROR);
                pe.setDetails(CAUGHT_ERROR, "1", new Object[] { ex });
                throw pe;
            }
        } else if (dataClass.isArray() && Byte.TYPE.equals(dataClass.getComponentType())) {
            byte[] dataBytes = (byte[]) data;
            ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(dataBytes,
                    context.getContentType());
            ((EntityEnclosingMethod) httpMethod).setRequestEntity(requestEntity);
        } else if (data instanceof InputStream) {
            InputStreamRequestEntity requestEntity = new InputStreamRequestEntity((InputStream) data,
                    context.getContentType());
            ((EntityEnclosingMethod) httpMethod).setRequestEntity(requestEntity);
        }
        //TODO: Support multipart post
        //else
        //{
        //FIXME: Throw exception if unhandled data type
        //}
    } else if (httpMethod instanceof GetMethod) {
        Object req = processBody(context);

        if (req instanceof String) {
            String requestString = (String) req;
            if (Log.isInfo()) {
                Logger logger = Log.getLogger(HTTPProxyService.LOG_CATEGORY);
                logger.debug(BEGIN + method + REQUEST);
                logger.debug(StringUtils.prettifyString(requestString));
                logger.debug(END + method + REQUEST);
            }

            if (!"".equals(requestString)) {
                String query = context.getHttpMethod().getQueryString();
                if (query != null) {
                    query += "&" + requestString;
                } else {
                    query = requestString;
                }
                context.getHttpMethod().setQueryString(query);
            }
        }
    }

    context.getHttpClient().setHostConfiguration(target.getHostConfig());

    try {
        context.getHttpClient().executeMethod(context.getHttpMethod());
    } catch (UnknownHostException uhex) {
        ProxyException pe = new ProxyException();
        pe.setMessage(UNKNOWN_HOST, new Object[] { uhex.getMessage() });
        pe.setCode(ProxyException.CODE_SERVER_PROXY_REQUEST_FAILED);
        throw pe;
    } catch (Exception ex) {
        // FIXME: JRB - could be more specific by looking for timeout and sending 504 in that case.
        // rfc2616 10.5.5 504 - could get more specific if we parse the HttpException
        ProxyException pe = new ProxyException(CAUGHT_ERROR);
        pe.setDetails(CAUGHT_ERROR, "1", new Object[] { ex.getMessage() });
        pe.setCode(ProxyException.CODE_SERVER_PROXY_REQUEST_FAILED);
        throw pe;
    }
}