List of usage examples for java.lang Class getComponentType
public Class<?> getComponentType()
From source file:org.codehaus.enunciate.modules.rest.RESTResourceExporter.java
/** * Handles a specific REST operation./* ww w .j ava 2 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:de.escalon.hypermedia.spring.SpringActionInputParameter.java
public Object[] getPossibleValues(MethodParameter methodParameter, ActionDescriptor actionDescriptor) { try {/*from w w w . ja va 2 s. c om*/ Class<?> parameterType = methodParameter.getNestedParameterType(); Object[] possibleValues; Class<?> nested; if (Enum[].class.isAssignableFrom(parameterType)) { possibleValues = parameterType.getComponentType().getEnumConstants(); } else if (Enum.class.isAssignableFrom(parameterType)) { possibleValues = parameterType.getEnumConstants(); } else if (Collection.class.isAssignableFrom(parameterType) && Enum.class.isAssignableFrom(nested = TypeDescriptor.nested(methodParameter, 1).getType())) { possibleValues = nested.getEnumConstants(); } else { Select select = methodParameter.getParameterAnnotation(Select.class); if (select != null) { Class<? extends Options> optionsClass = select.options(); Options options = optionsClass.newInstance(); // collect call values to pass to options.get List<Object> from = new ArrayList<Object>(); for (String paramName : select.args()) { ActionInputParameter parameterValue = actionDescriptor.getActionInputParameter(paramName); if (parameterValue != null) { from.add(parameterValue.getValue()); } } Object[] args = from.toArray(); possibleValues = options.get(select.value(), args); } else { possibleValues = new Object[0]; } } return possibleValues; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.comcast.cereal.engines.AbstractCerealEngine.java
@SuppressWarnings({ "rawtypes", "unchecked" }) public <T> T deCerealize(Object cereal, Class<T> clazz) throws CerealException { ObjectCache objectCache = new ObjectCache(settings); try {/*from ww w . jav a2s . c om*/ if (cereal instanceof List && clazz.isArray()) { List<Object> cerealList = (List) cereal; Class arrayType = clazz.getComponentType(); Cerealizer cerealizer = cerealFactory.getCerealizer(arrayType); T array = (T) Array.newInstance(arrayType, cerealList.size()); for (int i = 0; i < cerealList.size(); i++) { Array.set(array, i, cerealizer.deCerealize(cerealList.get(i), objectCache)); } return array; } else { Class<?> runtimeClass = cerealFactory.getRuntimeClass(cereal); Cerealizer cerealizer = cerealFactory.getCerealizer(clazz); if ((runtimeClass != null) && clazz.isAssignableFrom(runtimeClass)) { /** need to check if the runtime class is a subclass of the given class * or we will get a class cast exception when we return it */ cerealizer = cerealFactory.getRuntimeCerealizer(cereal, cerealizer); } return (T) cerealizer.deCerealize(cereal, objectCache); } } finally { objectCache.resetCache(); } }
From source file:org.apache.hadoop.hbase.security.access.HbaseObjectWritableFor96Migration.java
/** * Write a {@link Writable}, {@link String}, primitive type, or an array of * the preceding./*ww w . java 2 s.c om*/ * @param out * @param instance * @param declaredClass * @param conf * @throws IOException */ @SuppressWarnings("unchecked") static void writeObject(DataOutput out, Object instance, Class declaredClass, Configuration conf) throws IOException { Object instanceObj = instance; Class declClass = declaredClass; if (instanceObj == null) { // null instanceObj = new NullInstance(declClass, conf); declClass = Writable.class; } writeClassCode(out, declClass); if (declClass.isArray()) { // array // If bytearray, just dump it out -- avoid the recursion and // byte-at-a-time we were previously doing. if (declClass.equals(byte[].class)) { Bytes.writeByteArray(out, (byte[]) instanceObj); } else { //if it is a Generic array, write the element's type if (getClassCode(declaredClass) == GENERIC_ARRAY_CODE) { Class<?> componentType = declaredClass.getComponentType(); writeClass(out, componentType); } int length = Array.getLength(instanceObj); out.writeInt(length); for (int i = 0; i < length; i++) { Object item = Array.get(instanceObj, i); writeObject(out, item, item.getClass(), conf); } } } else if (List.class.isAssignableFrom(declClass)) { List list = (List) instanceObj; int length = list.size(); out.writeInt(length); for (int i = 0; i < length; i++) { Object elem = list.get(i); writeObject(out, elem, elem == null ? Writable.class : elem.getClass(), conf); } } else if (declClass == String.class) { // String Text.writeString(out, (String) instanceObj); } else if (declClass.isPrimitive()) { // primitive type if (declClass == Boolean.TYPE) { // boolean out.writeBoolean(((Boolean) instanceObj).booleanValue()); } else if (declClass == Character.TYPE) { // char out.writeChar(((Character) instanceObj).charValue()); } else if (declClass == Byte.TYPE) { // byte out.writeByte(((Byte) instanceObj).byteValue()); } else if (declClass == Short.TYPE) { // short out.writeShort(((Short) instanceObj).shortValue()); } else if (declClass == Integer.TYPE) { // int out.writeInt(((Integer) instanceObj).intValue()); } else if (declClass == Long.TYPE) { // long out.writeLong(((Long) instanceObj).longValue()); } else if (declClass == Float.TYPE) { // float out.writeFloat(((Float) instanceObj).floatValue()); } else if (declClass == Double.TYPE) { // double out.writeDouble(((Double) instanceObj).doubleValue()); } else if (declClass == Void.TYPE) { // void } else { throw new IllegalArgumentException("Not a primitive: " + declClass); } } else if (declClass.isEnum()) { // enum Text.writeString(out, ((Enum) instanceObj).name()); } else if (Message.class.isAssignableFrom(declaredClass)) { Text.writeString(out, instanceObj.getClass().getName()); ((Message) instance).writeDelimitedTo(DataOutputOutputStream.constructOutputStream(out)); } else if (Writable.class.isAssignableFrom(declClass)) { // Writable Class<?> c = instanceObj.getClass(); Integer code = CLASS_TO_CODE.get(c); if (code == null) { out.writeByte(NOT_ENCODED); Text.writeString(out, c.getName()); } else { writeClassCode(out, c); } ((Writable) instanceObj).write(out); } else if (Serializable.class.isAssignableFrom(declClass)) { Class<?> c = instanceObj.getClass(); Integer code = CLASS_TO_CODE.get(c); if (code == null) { out.writeByte(NOT_ENCODED); Text.writeString(out, c.getName()); } else { writeClassCode(out, c); } ByteArrayOutputStream bos = null; ObjectOutputStream oos = null; try { bos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(bos); oos.writeObject(instanceObj); byte[] value = bos.toByteArray(); out.writeInt(value.length); out.write(value); } finally { if (bos != null) bos.close(); if (oos != null) oos.close(); } } else if (Scan.class.isAssignableFrom(declClass)) { Scan scan = (Scan) instanceObj; byte[] scanBytes = ProtobufUtil.toScan(scan).toByteArray(); out.writeInt(scanBytes.length); out.write(scanBytes); } else { throw new IOException("Can't write: " + instanceObj + " as " + declClass); } }
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 ww .j a v a 2s. 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:org.eclipse.wb.internal.core.utils.reflect.ReflectionUtils.java
/** * @param runtime/*from w w w . j a va2 s .c o m*/ * is <code>true</code> if we need name for class loading, <code>false</code> if we need * name for source generation. * * @return the fully qualified name of given {@link Type}. */ public static String getFullyQualifiedName(Type type, boolean runtime) { Assert.isNotNull(type); // Class if (type instanceof Class<?>) { Class<?> clazz = (Class<?>) type; // array if (clazz.isArray()) { return getFullyQualifiedName(clazz.getComponentType(), runtime) + "[]"; } // object String name = clazz.getName(); if (!runtime) { name = name.replace('$', '.'); } return name; } // GenericArrayType if (type instanceof GenericArrayType) { GenericArrayType genericArrayType = (GenericArrayType) type; return getFullyQualifiedName(genericArrayType.getGenericComponentType(), runtime) + "[]"; } // ParameterizedType if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; Type rawType = parameterizedType.getRawType(); // raw type StringBuilder sb = new StringBuilder(); sb.append(getFullyQualifiedName(rawType, runtime)); // type arguments sb.append("<"); boolean firstTypeArgument = true; for (Type typeArgument : parameterizedType.getActualTypeArguments()) { if (!firstTypeArgument) { sb.append(","); } firstTypeArgument = false; sb.append(getFullyQualifiedName(typeArgument, runtime)); } sb.append(">"); // done return sb.toString(); } // WildcardType if (type instanceof WildcardType) { WildcardType wildcardType = (WildcardType) type; return "? extends " + getFullyQualifiedName(wildcardType.getUpperBounds()[0], runtime); } // TypeVariable TypeVariable<?> typeVariable = (TypeVariable<?>) type; return typeVariable.getName(); }
From source file:org.nabucco.alfresco.enhScriptEnv.common.script.converter.rhino.NativeArrayConverter.java
/** * {@inheritDoc}/*from w w w .j a v a 2 s .c o m*/ */ @Override public Object convertValueForJava(final Object value, final ValueConverter globalDelegate, final Class<?> expectedClass) { if (!(value instanceof NativeArray)) { throw new IllegalArgumentException("value must be a NativeArray"); } final NativeArray arr = (NativeArray) value; final Object[] ids = arr.getIds(); final Object result; if (expectedClass.isAssignableFrom(List.class) || expectedClass.isArray()) { final Class<?> expectedComponentClass = expectedClass.isArray() ? expectedClass.getComponentType() : Object.class; final List<Object> list = new ArrayList<Object>(); for (int idx = 0; idx < ids.length; idx++) { if (ids[idx] instanceof Integer) { final Object element = arr.get(((Integer) ids[idx]).intValue(), arr); final Object converted = globalDelegate.convertValueForJava(element, expectedComponentClass); list.add(converted); } } if (expectedClass.isArray()) { final Object newArr = Array.newInstance(expectedComponentClass, list.size()); for (int idx = 0; idx < list.size(); idx++) { Array.set(newArr, idx, list.get(idx)); } result = newArr; } else { result = list; } } else { final Map<Object, Object> propValues = new HashMap<Object, Object>(ids.length); for (final Object propId : ids) { final Object val = arr.get(propId.toString(), arr); final Object convertedKey = globalDelegate.convertValueForJava(propId); final Object convertedValue = globalDelegate.convertValueForJava(val); propValues.put(convertedKey, convertedValue); } result = propValues; } return result; }
From source file:com.github.helenusdriver.driver.impl.DataTypeImpl.java
/** * Infers the data type for the specified field once it has already been * processed for optional and collections. * * @author paouelle//from ww w .ja va 2 s . c o m * * @param field the non-<code>null</code> field to infer the CQL data type for * @param clazz the non-<code>null</code> class for which to infer the CQL * data type for the field * @param types the non-<code>null</code> list where to add the inferred type and * its arguments * @param persisted the persisted annotation to consider for the field * @throws IllegalArgumentException if the data type cannot be inferred from * the field */ private static void inferBasicDataTypeFrom(Field field, Class<?> clazz, List<CQLDataType> types, Persisted persisted) { if (persisted != null) { types.add(persisted.as()); } else if (String.class == clazz) { types.add(DataType.TEXT); } else if (Integer.class == clazz) { types.add(DataType.INT); } else if (Long.class == clazz) { types.add(DataType.BIGINT); } else if (Boolean.class == clazz) { types.add(DataType.BOOLEAN); } else if (Date.class.isAssignableFrom(clazz)) { types.add(DataType.TIMESTAMP); } else if (Double.class == clazz) { types.add(DataType.DOUBLE); } else if (Float.class == clazz) { types.add(DataType.FLOAT); } else if (UUID.class.isAssignableFrom(clazz)) { types.add(DataType.UUID); } else if ((clazz.isArray() && (Byte.TYPE == clazz.getComponentType())) || ByteBuffer.class.isAssignableFrom(clazz)) { types.add(DataType.BLOB); } else if (BigDecimal.class.isAssignableFrom(clazz)) { types.add(DataType.DECIMAL); } else if (BigInteger.class.isAssignableFrom(clazz)) { types.add(DataType.VARINT); } else if (InetAddress.class.isAssignableFrom(clazz)) { types.add(DataType.INET); } else if (AtomicLong.class.isAssignableFrom(clazz)) { types.add(DataType.COUNTER); } else if (clazz.isEnum()) { types.add(DataType.ASCII); } else if (Class.class == clazz) { types.add(DataType.ASCII); } else if (Locale.class == clazz) { types.add(DataType.ASCII); } else if (ZoneId.class.isAssignableFrom(clazz)) { types.add(DataType.ASCII); } else if (Instant.class == clazz) { types.add(DataType.TIMESTAMP); } else { // check if it is a user-defined type try { final ClassInfoImpl<?> cinfo = (ClassInfoImpl<?>) StatementBuilder.getClassInfo(clazz); org.apache.commons.lang3.Validate.isTrue(cinfo instanceof UDTClassInfoImpl, "unable to infer data type in field: %s", field); types.add((UDTClassInfoImpl<?>) cinfo); } catch (Exception e) { throw new IllegalArgumentException("unable to infer data type in field: " + field, e); } } }
From source file:org.nabucco.alfresco.enhScriptEnv.common.script.converter.rhino.NativeArrayConverter.java
/** * {@inheritDoc}/* w w w . j a va2 s .c om*/ */ @Override public boolean canConvertValueForJava(final Object value, final ValueConverter globalDelegate, final Class<?> expectedClass) { boolean canConvert = value instanceof NativeArray; if (canConvert) { if (expectedClass.isAssignableFrom(List.class) || expectedClass.isArray()) { final NativeArray arr = (NativeArray) value; final Object[] ids = arr.getIds(); canConvert = this.isArray(ids); if (canConvert) { final Class<?> expectedComponentClass = expectedClass.isArray() ? expectedClass.getComponentType() : Object.class; for (int idx = 0; idx < ids.length && canConvert; idx++) { if (ids[idx] instanceof Integer) { final Object element = arr.get(((Integer) ids[idx]).intValue(), arr); canConvert = canConvert && globalDelegate.canConvertValueForJava(element, expectedComponentClass); } } } } else { canConvert = expectedClass.isAssignableFrom(Map.class); if (canConvert) { final NativeArray arr = (NativeArray) value; final Object[] ids = arr.getIds(); for (final Object propId : ids) { final Object val = arr.get(propId.toString(), arr); canConvert = canConvert && globalDelegate.canConvertValueForJava(propId) && globalDelegate.canConvertValueForJava(val); if (!canConvert) { break; } } } } } return canConvert; }
From source file:org.evosuite.utils.generic.GenericClass.java
protected static Type addTypeParameters(Class<?> clazz) { if (clazz.isArray()) { return GenericArrayTypeImpl.createArrayType(addTypeParameters(clazz.getComponentType())); } else if (isMissingTypeParameters(clazz)) { TypeVariable<?>[] vars = clazz.getTypeParameters(); // Type[] arguments = new Type[vars.length]; // Arrays.fill(arguments, UNBOUND_WILDCARD); Type owner = clazz.getDeclaringClass() == null ? null : addTypeParameters(clazz.getDeclaringClass()); return new ParameterizedTypeImpl(clazz, vars, owner); } else {//w w w . j a v a 2 s . c om return clazz; } }