List of usage examples for java.lang Class isPrimitive
@HotSpotIntrinsicCandidate public native boolean isPrimitive();
From source file:fr.certu.chouette.command.Command.java
private void removeAttribute(Object object, String attrname, String value) throws Exception { Class<?> beanClass = object.getClass(); Method adder = findAdder(beanClass, attrname); Class<?> type = adder.getParameterTypes()[0]; if (type.getName().startsWith("fr.certu.chouette.model.neptune") && !type.getName().startsWith("Enum")) { type = Integer.TYPE;/*from w w w . j av a 2s.c om*/ } else { } Method remover = findRemover(beanClass, attrname, type); Object arg = null; if (type.isEnum()) { arg = toEnum(type, value); } else if (type.isPrimitive()) { arg = toPrimitive(type, value); } else { arg = toObject(type, value); } remover.invoke(object, arg); }
From source file:fr.certu.chouette.command.Command.java
/** * @param object/*from ww w . ja v a2 s .c o m*/ * @param attrname * @param value * @throws Exception */ private void setAttribute(Object object, String attrname, String value) throws Exception { String name = attrname.toLowerCase(); if (name.equals("id")) { throw new Exception("non writable attribute id for any object , process stopped "); } if (!name.equals("objectid") && !name.equals("creatorid") && !name.equals("areacentroid") && name.endsWith("id")) { throw new Exception( "non writable attribute " + attrname + " use setReference instand , process stopped "); } Class<?> beanClass = object.getClass(); Method setter = findSetter(beanClass, attrname); Class<?> type = setter.getParameterTypes()[0]; if (type.isArray() || type.getSimpleName().equals("List")) { throw new Exception("list attribute " + attrname + " for object " + beanClass.getName() + " must be update with (add/remove)Attribute, process stopped "); } Object arg = null; if (type.isEnum()) { arg = toEnum(type, value); } else if (type.isPrimitive()) { arg = toPrimitive(type, value); } else { arg = toObject(type, value); } setter.invoke(object, arg); }
From source file:org.ajax4jsf.util.SelectUtils.java
/** * Converts UISelectMany submitted value to converted value * //w w w. j ava 2s. c o m * @author Manfred Geiler * @param facesContext * @param component * @param submittedValue * @return * @throws ConverterException */ public static Object getConvertedUISelectManyValue(FacesContext facesContext, UISelectMany component, String[] submittedValue) throws ConverterException { // Attention! // This code is duplicated in jsfapi component package. // If you change something here please do the same in the other class! if (submittedValue == null) throw new NullPointerException("submittedValue"); ELContext elContext = facesContext.getELContext(); ValueExpression vb = component.getValueExpression("value"); Class<?> valueType = null; Class<?> arrayComponentType = null; if (vb != null) { valueType = vb.getType(elContext); if (valueType != null && valueType.isArray()) { arrayComponentType = valueType.getComponentType(); } } Converter converter = component.getConverter(); if (converter == null) { if (valueType == null) { // No converter, and no idea of expected type // --> return the submitted String array return submittedValue; } if (List.class.isAssignableFrom(valueType)) { // expected type is a List // --> according to javadoc of UISelectMany we assume that the // element type // is java.lang.String, and copy the String array to a new List List<String> lst = Arrays.asList(submittedValue); return lst; } if (arrayComponentType == null) { throw new IllegalArgumentException(Messages.getMessage(Messages.VALUE_BINDING_TYPE_ERROR)); } if (String.class.equals(arrayComponentType)) return submittedValue; // No conversion needed for String type if (Object.class.equals(arrayComponentType)) return submittedValue; // No conversion for Object class try { converter = facesContext.getApplication().createConverter(arrayComponentType); } catch (FacesException e) { log.error(Messages.getMessage(Messages.NO_CONVERTER_FOUND_ERROR, arrayComponentType.getName()), e); return submittedValue; } } // Now, we have a converter... if (valueType == null) { // ...but have no idea of expected type // --> so let's convert it to an Object array int len = submittedValue.length; Object[] convertedValues = (Object[]) Array .newInstance(arrayComponentType == null ? Object.class : arrayComponentType, len); for (int i = 0; i < len; i++) { convertedValues[i] = converter.getAsObject(facesContext, component, submittedValue[i]); } return convertedValues; } if (List.class.isAssignableFrom(valueType)) { // Curious case: According to specs we should assume, that the // element type // of this List is java.lang.String. But there is a Converter set // for this // component. Because the user must know what he is doing, we will // convert the values. int len = submittedValue.length; List<Object> lst = new ArrayList<Object>(len); for (int i = 0; i < len; i++) { lst.add(converter.getAsObject(facesContext, component, submittedValue[i])); } return lst; } if (arrayComponentType == null) { throw new IllegalArgumentException(Messages.getMessage(Messages.VALUE_BINDING_TYPE_ERROR)); } if (arrayComponentType.isPrimitive()) { // primitive array int len = submittedValue.length; Object convertedValues = Array.newInstance(arrayComponentType, len); for (int i = 0; i < len; i++) { Array.set(convertedValues, i, converter.getAsObject(facesContext, component, submittedValue[i])); } return convertedValues; } else { // Object array int len = submittedValue.length; ArrayList<Object> convertedValues = new ArrayList<Object>(len); for (int i = 0; i < len; i++) { convertedValues.add(i, converter.getAsObject(facesContext, component, submittedValue[i])); } return convertedValues.toArray((Object[]) Array.newInstance(arrayComponentType, len)); } }
From source file:org.crank.javax.faces.component.MenuRenderer.java
protected Object convertSelectManyValues(FacesContext context, UISelectMany uiSelectMany, Class<?> arrayClass, String[] newValues) throws ConverterException { Object result = null;/*from w w w .j a va 2 s.co m*/ Converter converter = null; int len = (null != newValues ? newValues.length : 0); Class<?> elementType = arrayClass.getComponentType(); // Optimization: If the elementType is String, we don't need // conversion. Just return newValues. if (elementType.equals(String.class)) { return newValues; } try { result = Array.newInstance(elementType, len); } catch (Exception e) { throw new ConverterException(e); } // bail out now if we have no new values, returning our // oh-so-useful zero-length array. if (null == newValues) { return result; } // obtain a converter. // attached converter takes priority if (null == (converter = uiSelectMany.getConverter())) { // Otherwise, look for a by-type converter if (null == (converter = Util.getConverterForClass(elementType, context))) { // if that fails, and the attached values are of Object type, // we don't need conversion. if (elementType.equals(Object.class)) { return newValues; } StringBuffer valueStr = new StringBuffer(); for (int i = 0; i < len; i++) { if (i == 0) { valueStr.append(newValues[i]); } else { valueStr.append(' ').append(newValues[i]); } } Object[] params = { valueStr.toString(), "null Converter" }; throw new ConverterException( MessageUtils.getExceptionMessage(MessageUtils.CONVERSION_ERROR_MESSAGE_ID, params)); } } assert (null != result); if (elementType.isPrimitive()) { for (int i = 0; i < len; i++) { if (elementType.equals(Boolean.TYPE)) { Array.setBoolean(result, i, ((Boolean) converter.getAsObject(context, uiSelectMany, newValues[i]))); } else if (elementType.equals(Byte.TYPE)) { Array.setByte(result, i, ((Byte) converter.getAsObject(context, uiSelectMany, newValues[i]))); } else if (elementType.equals(Double.TYPE)) { Array.setDouble(result, i, ((Double) converter.getAsObject(context, uiSelectMany, newValues[i]))); } else if (elementType.equals(Float.TYPE)) { Array.setFloat(result, i, ((Float) converter.getAsObject(context, uiSelectMany, newValues[i]))); } else if (elementType.equals(Integer.TYPE)) { Array.setInt(result, i, ((Integer) converter.getAsObject(context, uiSelectMany, newValues[i]))); } else if (elementType.equals(Character.TYPE)) { Array.setChar(result, i, ((Character) converter.getAsObject(context, uiSelectMany, newValues[i]))); } else if (elementType.equals(Short.TYPE)) { Array.setShort(result, i, ((Short) converter.getAsObject(context, uiSelectMany, newValues[i]))); } else if (elementType.equals(Long.TYPE)) { Array.setLong(result, i, ((Long) converter.getAsObject(context, uiSelectMany, newValues[i]))); } } } else { for (int i = 0; i < len; i++) { if (logger.isLoggable(Level.FINE)) { Object converted = converter.getAsObject(context, uiSelectMany, newValues[i]); logger.fine("String value: " + newValues[i] + " converts to : " + converted.toString()); } Array.set(result, i, converter.getAsObject(context, uiSelectMany, newValues[i])); } } return result; }
From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java
private static Object deproxyObject(Class<?> targetClass, Object proxy) throws InstantiationException, IllegalAccessException, IntrospectionException, InvocationTargetException, PersistenceException, ClassNotFoundException { Object target = targetClass.newInstance(); PropertyDescriptor[] targetPds = Introspector.getBeanInfo(targetClass).getPropertyDescriptors(); for (PropertyDescriptor targetPd : targetPds) { if (targetPd.getReadMethod() != null && targetPd.getWriteMethod() != null) { Object o = targetPd.getReadMethod().invoke(proxy, new Object[0]); if (o != null) { Class<?> propertyType = targetPd.getPropertyType(); String className = propertyType.getName(); if (!propertyType.isPrimitive() && !o.getClass().isPrimitive() && !(o instanceof Date) && isProxy(o, className)) { if (Set.class.isAssignableFrom(propertyType)) { o = new LazySet(); } else if (List.class.isAssignableFrom(propertyType)) { o = new LazyList(); } else o = newLazyObject(propertyType); }// w w w. j a va 2s . c om targetPd.getWriteMethod().invoke(target, o); } } } return target; }
From source file:com.xiovr.unibot.bot.impl.BotGameConfigImpl.java
@SuppressWarnings("unchecked") @Override/*www.j a v a 2 s .co m*/ public void saveSettings(Settings instance, String fn, String comment) { Class<?> clazz = instance.getClass().getInterfaces()[0]; Class<?> invocableClazz = instance.getClass(); // File file = new File("/" + DIR_PATH + "/" + fn); File file = new File(fn); Properties props = new SortedProperties(); Method[] methods = clazz.getMethods(); for (Method method : methods) { // Find setters if (method.getName().startsWith("set")) { if (method.isAnnotationPresent(Param.class)) { Annotation annotation = method.getAnnotation(Param.class); Param param = (Param) annotation; if (param.name().equals("") || param.values().length == 0) { throw new RuntimeException("Wrong param in class " + clazz.getCanonicalName() + " with method " + method.getName()); } Class<?>[] paramClazzes = method.getParameterTypes(); if (paramClazzes.length != 1) { throw new RuntimeException("Error contract design in class " + clazz.getCanonicalName() + " with method " + method.getName()); } // Check param belongs to List Class<?> paramClazz = paramClazzes[0]; try { if (List.class.isAssignableFrom(paramClazz)) { // Oh, its array... // May be its InetSocketAddress? Type[] gpt = method.getGenericParameterTypes(); if (gpt[0] instanceof ParameterizedType) { ParameterizedType type = (ParameterizedType) gpt[0]; Type[] typeArguments = type.getActualTypeArguments(); for (Type typeArgument : typeArguments) { Class<?> classType = ((Class<?>) typeArgument); if (InetSocketAddress.class.isAssignableFrom(classType)) { List<InetSocketAddress> isaArr = (List<InetSocketAddress>) invocableClazz .getMethod("get" + method.getName().substring(3)).invoke(instance); int cnt = isaArr.size(); props.setProperty(param.name() + ".count", String.valueOf(cnt)); for (int i = 0; i < cnt; ++i) { props.setProperty(param.name() + "." + String.valueOf(i) + ".ip", isaArr.get(i).getHostString()); props.setProperty(param.name() + "." + String.valueOf(i) + ".port", String.valueOf(isaArr.get(i).getPort())); } } else { throw new RuntimeException("Settings param in class " + clazz.getCanonicalName() + " with method " + method.getName() + " not implemented yet"); } } } } else if (paramClazz.isPrimitive()) { props.setProperty(param.name(), String.valueOf(invocableClazz .getMethod("get" + method.getName().substring(3)).invoke(instance))); } else if (String.class.isAssignableFrom(paramClazz)) { props.setProperty(param.name(), (String) (invocableClazz .getMethod("get" + method.getName().substring(3)).invoke(instance))); } else { throw new RuntimeException("Settings param in class " + clazz.getCanonicalName() + " with method " + method.getName() + " not implemented yet"); } BotUtils.saveProperties(file, props, "Bot v" + VERSION); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | IOException e) { e.printStackTrace(); } } } } }
From source file:com.opensymphony.xwork2.conversion.impl.XWorkBasicConverter.java
@Override public Object convertValue(Map<String, Object> context, Object o, Member member, String s, Object value, Class toType) { Object result = null;/* w ww . ja va 2 s . co m*/ if (value == null || toType.isAssignableFrom(value.getClass())) { // no need to convert at all, right? return value; } if (toType == String.class) { /* the code below has been disabled as it causes sideffects in Struts2 (XW-512) // if input (value) is a number then use special conversion method (XW-490) Class inputType = value.getClass(); if (Number.class.isAssignableFrom(inputType)) { result = doConvertFromNumberToString(context, value, inputType); if (result != null) { return result; } }*/ // okay use default string conversion result = doConvertToString(context, value); } else if (toType == boolean.class) { result = doConvertToBoolean(value); } else if (toType == Boolean.class) { result = doConvertToBoolean(value); } else if (toType.isArray()) { result = doConvertToArray(context, o, member, s, value, toType); } else if (Date.class.isAssignableFrom(toType)) { result = doConvertToDate(context, value, toType); } else if (Calendar.class.isAssignableFrom(toType)) { Date dateResult = (Date) doConvertToDate(context, value, Date.class); if (dateResult != null) { Calendar calendar = Calendar.getInstance(); calendar.setTime(dateResult); result = calendar; } } else if (Collection.class.isAssignableFrom(toType)) { result = doConvertToCollection(context, o, member, s, value, toType); } else if (toType == Character.class) { result = doConvertToCharacter(value); } else if (toType == char.class) { result = doConvertToCharacter(value); } else if (Number.class.isAssignableFrom(toType) || toType.isPrimitive()) { result = doConvertToNumber(context, value, toType); } else if (toType == Class.class) { result = doConvertToClass(value); } if (result == null) { if (value instanceof Object[]) { Object[] array = (Object[]) value; if (array.length >= 1) { value = array[0]; } else { value = null; } // let's try to convert the first element only result = convertValue(context, o, member, s, value, toType); } else if (!"".equals(value)) { // we've already tried the types we know result = super.convertValue(context, value, toType); } if (result == null && value != null && !"".equals(value)) { throw new XWorkException("Cannot create type " + toType + " from value " + value); } } return result; }
From source file:org.wrml.runtime.schema.generator.SchemaGenerator.java
private Value generateValue(final Type heapValueType, final ProtoSlot protoSlot) { final Context context = getContext(); if (heapValueType == null) { return null; }//from www .java 2s .c o m final SchemaLoader schemaLoader = context.getSchemaLoader(); final ValueType valueType = schemaLoader.getValueType(heapValueType); final Class<?> heapValueClass = (heapValueType instanceof Class<?>) ? (Class<?>) heapValueType : null; final boolean requiresNonNullValue = (heapValueClass != null && heapValueClass.isPrimitive()); Value value = null; switch (valueType) { case Boolean: final BooleanValue booleanValue = context.newModel(BooleanValue.class); value = booleanValue; break; case Date: final DateValue dateValue = context.newModel(DateValue.class); value = dateValue; break; case Double: final DoubleValue doubleValue = context.newModel(DoubleValue.class); value = doubleValue; break; case Integer: final IntegerValue integerValue = context.newModel(IntegerValue.class); value = integerValue; break; case Link: final LinkValue linkValue = context.newModel(LinkValue.class); if (protoSlot instanceof LinkProtoSlot) { final LinkProtoSlot linkProtoSlot = (LinkProtoSlot) protoSlot; linkValue.setLinkRelationUri(linkProtoSlot.getLinkRelationUri()); linkValue.setEmbedded(linkProtoSlot.isEmbedded()); linkValue.setRequestSchemaUri(linkProtoSlot.getRequestSchemaUri()); linkValue.setResponseSchemaUri(linkProtoSlot.getResponseSchemaUri()); final List<LinkValueBinding> bindings = generateLinkValueBindingList(linkProtoSlot); linkValue.getBindings().addAll(bindings); } value = linkValue; break; case Model: final ModelValue modelValue = context.newModel(ModelValue.class); final URI modelSchemaUri = schemaLoader.getTypeUri(heapValueClass); modelValue.setModelSchemaUri(modelSchemaUri); value = modelValue; break; case List: final ListValue listValue; if (protoSlot instanceof CollectionPropertyProtoSlot) { final CollectionPropertyProtoSlot collectionPropertyProtoSlot = (CollectionPropertyProtoSlot) protoSlot; final CollectionValue collectionValue = context.newModel(CollectionValue.class); listValue = collectionValue; final Integer limit = collectionPropertyProtoSlot.getLimit(); if (limit != null && limit > 0) { collectionValue.setLimit(limit); } final URI linkRelationUri = collectionPropertyProtoSlot.getLinkRelationUri(); if (linkRelationUri != null) { collectionValue.setLinkRelationUri(linkRelationUri); } final ProtoSearchCriteria protoSearchCriteria = collectionPropertyProtoSlot .getProtoSearchCriteria(); final List<CollectionValueSearchCriterion> and = generateCollectionValueSearchCriterionList( protoSearchCriteria.getAnd()); collectionValue.getAnd().addAll(and); final List<CollectionValueSearchCriterion> or = generateCollectionValueSearchCriterionList( protoSearchCriteria.getOr()); collectionValue.getOr().addAll(or); } else { listValue = context.newModel(ListValue.class); } final Slot elementSlot = context.newModel(Slot.class); // TODO get this from the java class elementSlot.setName("E"); final Type elementValueHeapType = ValueType.getListElementType(heapValueType); final Value elementValue = generateValue(elementValueHeapType, null); elementSlot.setValue(elementValue); listValue.setElementSlot(elementSlot); value = listValue; break; case Long: final LongValue longValue = context.newModel(LongValue.class); value = longValue; break; case Native: break; case SingleSelect: final SingleSelectValue singleSelectValue = context.newModel(SingleSelectValue.class); singleSelectValue.setChoicesUri(schemaLoader.getTypeUri(heapValueType)); value = singleSelectValue; break; case Text: final TextValue textValue = context.newModel(TextValue.class); if (!String.class.equals(heapValueType) && heapValueClass != null) { final SyntaxLoader syntaxLoader = context.getSyntaxLoader(); final URI syntaxUri = syntaxLoader.getSyntaxUri(heapValueClass); textValue.setSyntaxUri(syntaxUri); } value = textValue; break; default: break; } if (value instanceof MaybeRequired && requiresNonNullValue) { ((MaybeRequired) value).setRequired(requiresNonNullValue); } return value; }
From source file:jp.furplag.util.commons.NumberUtilsTest.java
/** * {@link jp.furplag.util.commons.NumberUtils#valueOf(java.lang.Object, java.lang.Class, boolean)}. *///from ww w. ja va 2 s . c o m @SuppressWarnings("unchecked") @Test public void testValueOfObjectClassOfTBoolean() { assertEquals("null", null, valueOf(null, null, false)); assertEquals("null: fallback", null, valueOf(null, null, true)); try { for (Class<?> type : NUMBERS) { Object o = null; Object expected = null; Class<? extends Number> wrapper = (Class<? extends Number>) ClassUtils.primitiveToWrapper(type); if (type.isPrimitive()) expected = wrapper.getMethod("valueOf", String.class).invoke(null, "0"); assertEquals("null: " + type.getSimpleName(), expected, valueOf(o, (Class<? extends Number>) type, false)); if (ClassUtils.isPrimitiveWrapper(wrapper)) { expected = wrapper.getMethod("valueOf", String.class).invoke(null, "0"); } else { expected = wrapper.getField("ZERO").get(null); } assertEquals("null: fallback: " + type.getSimpleName(), expected, valueOf(o, (Class<? extends Number>) type, true)); assertEquals("null: typeEquals: " + type.getSimpleName(), ClassUtils.primitiveToWrapper(expected.getClass()), valueOf(o, (Class<? extends Number>) type, true).getClass()); o = Float.NaN; expected = !type.isPrimitive() ? null : wrapper.getMethod("valueOf", String.class).invoke(null, "0"); if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) expected = wrapper.getMethod("valueOf", String.class).invoke(null, "NaN"); assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected, valueOf(o, (Class<? extends Number>) type, false)); if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) { expected = wrapper.getMethod("valueOf", String.class).invoke(null, "NaN"); } else if (ClassUtils.isPrimitiveWrapper(wrapper)) { expected = wrapper.getMethod("valueOf", String.class).invoke(null, "0"); } else { expected = wrapper.getField("ZERO").get(null); } assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected, valueOf(o, (Class<? extends Number>) type, true)); assertEquals(o + "(" + o.getClass() + "): typeEquals: " + type, ClassUtils.primitiveToWrapper(expected.getClass()), valueOf(o, (Class<? extends Number>) type, true).getClass()); o = Double.NaN; expected = !type.isPrimitive() ? null : wrapper.getMethod("valueOf", String.class).invoke(null, "0"); if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) expected = wrapper.getMethod("valueOf", String.class).invoke(null, "NaN"); assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected, valueOf(o, (Class<? extends Number>) type, false)); if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) { expected = wrapper.getMethod("valueOf", String.class).invoke(null, "NaN"); } else if (ClassUtils.isPrimitiveWrapper(wrapper)) { expected = wrapper.getMethod("valueOf", String.class).invoke(null, "0"); } else { expected = wrapper.getField("ZERO").get(null); } assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected, valueOf(o, (Class<? extends Number>) type, true)); assertEquals(o + "(" + o.getClass() + "): typeEquals: " + type, ClassUtils.primitiveToWrapper(expected.getClass()), valueOf(o, (Class<? extends Number>) type, true).getClass()); if (ClassUtils.isPrimitiveWrapper(wrapper)) { expected = wrapper.getMethod("valueOf", String.class).invoke(null, "1"); } else { expected = wrapper.getField("ONE").get(null); } for (Class<?> valueType : OBJECTS) { if (ClassUtils.isPrimitiveWrapper(valueType)) { o = valueType.getMethod("valueOf", String.class).invoke(null, "1"); } else { o = valueType.getField("ONE").get(null); } assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected, valueOf(o, (Class<? extends Number>) type, false)); assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected, valueOf(o, (Class<? extends Number>) type, true)); assertEquals(o + "(" + o.getClass() + "): typeEquals: " + type, ClassUtils.primitiveToWrapper(expected.getClass()), valueOf(o, (Class<? extends Number>) type, true).getClass()); } if (ClassUtils.isPrimitiveWrapper(wrapper)) { expected = wrapper.getMethod("valueOf", String.class).invoke(null, "-123"); } else { Constructor<?> c = type.getDeclaredConstructor(String.class); expected = c.newInstance("-123"); } for (Class<?> valueType : OBJECTS) { if (ClassUtils.isPrimitiveWrapper(valueType)) { o = valueType.getMethod("valueOf", String.class).invoke(null, "-123"); } else { Constructor<?> c = valueType.getDeclaredConstructor(String.class); o = c.newInstance("-123"); } assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected, valueOf(o, (Class<? extends Number>) type, false)); assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected, valueOf(o, (Class<? extends Number>) type, true)); assertEquals(o + "(" + o.getClass() + "): typeEquals: " + type, ClassUtils.primitiveToWrapper(expected.getClass()), valueOf(o, (Class<? extends Number>) type, true).getClass()); } if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) { expected = wrapper.getMethod("valueOf", String.class).invoke(null, "123.456"); } else if (ClassUtils.isPrimitiveWrapper(wrapper)) { expected = wrapper.getMethod("valueOf", String.class).invoke(null, "123"); } else { Constructor<?> c = type.getDeclaredConstructor(String.class); expected = c.newInstance(BigInteger.class.equals(type) ? "123" : "123.456"); } for (Class<?> valueType : OBJECTS) { if (ObjectUtils.isAny(valueType, Double.class, Float.class)) { o = valueType.getMethod("valueOf", String.class).invoke(null, "123.456"); } else if (BigDecimal.class.equals(valueType)) { Constructor<?> c = valueType.getDeclaredConstructor(String.class); o = c.newInstance("123.456"); } else { continue; } assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected, valueOf(o, (Class<? extends Number>) type, false)); assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected, valueOf(o, (Class<? extends Number>) type, true)); assertEquals(o + "(" + o.getClass() + "): typeEquals: " + type, ClassUtils.primitiveToWrapper(expected.getClass()), valueOf(o, (Class<? extends Number>) type, true).getClass()); } if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) { expected = wrapper.getMethod("valueOf", String.class).invoke(null, "-123.456"); } else if (ClassUtils.isPrimitiveWrapper(wrapper)) { expected = wrapper.getMethod("valueOf", String.class).invoke(null, "-123"); } else { Constructor<?> c = type.getDeclaredConstructor(String.class); expected = c.newInstance(BigInteger.class.equals(type) ? "-123" : "-123.456"); } for (Class<?> valueType : OBJECTS) { if (ObjectUtils.isAny(valueType, Double.class, Float.class)) { o = valueType.getMethod("valueOf", String.class).invoke(null, "-123.456"); } else if (BigDecimal.class.equals(valueType)) { Constructor<?> c = valueType.getDeclaredConstructor(String.class); o = c.newInstance("-123.456"); } else { continue; } assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected, valueOf(o, (Class<? extends Number>) type, false)); assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected, valueOf(o, (Class<? extends Number>) type, true)); assertEquals(o + "(" + o.getClass() + "): typeEquals: " + type, ClassUtils.primitiveToWrapper(expected.getClass()), valueOf(o, (Class<? extends Number>) type, true).getClass()); } o = INFINITY_DOUBLE.pow(2); if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) { expected = wrapper.getField("POSITIVE_INFINITY").get(null); } else if (ClassUtils.isPrimitiveWrapper(wrapper)) { expected = wrapper.getField("MAX_VALUE").get(null); } else { expected = BigInteger.class.equals(type) ? INFINITY_DOUBLE.pow(2).toBigInteger() : INFINITY_DOUBLE.pow(2); } assertEquals("Huge: (" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected, valueOf(o, (Class<? extends Number>) type, false)); assertEquals("Huge: (" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected, valueOf(o, (Class<? extends Number>) type, true)); assertEquals("Huge: (" + o.getClass() + "): typeEquals: " + type, ClassUtils.primitiveToWrapper(expected.getClass()), valueOf(o, (Class<? extends Number>) type, true).getClass()); o = INFINITY_DOUBLE.pow(2).negate(); if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) { expected = wrapper.getField("NEGATIVE_INFINITY").get(null); } else if (ClassUtils.isPrimitiveWrapper(wrapper)) { expected = wrapper.getField("MIN_VALUE").get(null); } else { expected = BigInteger.class.equals(type) ? INFINITY_DOUBLE.pow(2).toBigInteger().negate() : INFINITY_DOUBLE.pow(2).negate(); } assertEquals("Huge: (" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected, valueOf(o, (Class<? extends Number>) type, false)); assertEquals("Huge: (" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected, valueOf(o, (Class<? extends Number>) type, true)); assertEquals("Huge: (" + o.getClass() + "): typeEquals: " + type, ClassUtils.primitiveToWrapper(expected.getClass()), valueOf(o, (Class<? extends Number>) type, true).getClass()); o = INFINITY_DOUBLE.pow(2).toBigInteger(); if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) { expected = wrapper.getField("POSITIVE_INFINITY").get(null); } else if (ClassUtils.isPrimitiveWrapper(wrapper)) { expected = wrapper.getField("MAX_VALUE").get(null); } else { expected = BigInteger.class.equals(type) ? INFINITY_DOUBLE.pow(2).toBigInteger() : INFINITY_DOUBLE.pow(2); } assertEquals("Huge: (" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected, valueOf(o, (Class<? extends Number>) type, false)); assertEquals("Huge: (" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected, valueOf(o, (Class<? extends Number>) type, true)); assertEquals("Huge: (" + o.getClass() + "): typeEquals: " + type, ClassUtils.primitiveToWrapper(expected.getClass()), valueOf(o, (Class<? extends Number>) type, true).getClass()); o = INFINITY_DOUBLE.pow(2).toBigInteger().negate(); if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) { expected = wrapper.getField("NEGATIVE_INFINITY").get(null); } else if (ClassUtils.isPrimitiveWrapper(wrapper)) { expected = wrapper.getField("MIN_VALUE").get(null); } else { expected = BigInteger.class.equals(type) ? INFINITY_DOUBLE.pow(2).toBigInteger().negate() : INFINITY_DOUBLE.pow(2).negate(); } assertEquals("Huge: (" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected, valueOf(o, (Class<? extends Number>) type, false)); assertEquals("Huge: (" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected, valueOf(o, (Class<? extends Number>) type, true)); assertEquals("Huge: (" + o.getClass() + "): typeEquals: " + type, ClassUtils.primitiveToWrapper(expected.getClass()), valueOf(o, (Class<? extends Number>) type, true).getClass()); o = ""; expected = !type.isPrimitive() ? null : wrapper.getMethod("valueOf", String.class).invoke(null, "0"); assertEquals("\"" + o + "\": " + type.getSimpleName(), expected, valueOf(o, (Class<? extends Number>) type, false)); if (ClassUtils.isPrimitiveWrapper(wrapper)) { expected = wrapper.getMethod("valueOf", String.class).invoke(null, "0"); } else { expected = wrapper.getField("ZERO").get(null); } assertEquals("\"" + o + "\": fallback: " + type.getSimpleName(), expected, valueOf(o, (Class<? extends Number>) type, true)); assertEquals("\"" + o + "\": typeEquals: " + type.getSimpleName(), ClassUtils.primitiveToWrapper(expected.getClass()), valueOf(o, (Class<? extends Number>) type, true).getClass()); o = "1"; if (ClassUtils.isPrimitiveWrapper(wrapper)) { expected = wrapper.getMethod("valueOf", String.class).invoke(null, "1"); } else { expected = wrapper.getField("ONE").get(null); } assertEquals("\"" + o + "\": " + type.getSimpleName(), expected, valueOf(o, (Class<? extends Number>) type, false)); assertEquals("\"" + o + "\": " + type.getSimpleName(), expected, valueOf(o, (Class<? extends Number>) type, true)); assertEquals("\"" + o + "\": typeEquals: " + type, ClassUtils.primitiveToWrapper(expected.getClass()), valueOf(o, (Class<? extends Number>) type, true).getClass()); o = "-123456E-3"; if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) { expected = wrapper.getMethod("valueOf", String.class).invoke(null, "-123.456"); } else if (ClassUtils.isPrimitiveWrapper(wrapper)) { expected = wrapper.getMethod("valueOf", String.class).invoke(null, "-123"); } else { Constructor<?> c = type.getDeclaredConstructor(String.class); expected = c.newInstance(BigInteger.class.equals(type) ? "-123" : "-123.456"); } assertEquals("\"" + o + "\": " + type.getSimpleName(), expected, valueOf(o, (Class<? extends Number>) type, false)); assertEquals("\"" + o + "\": " + type.getSimpleName(), expected, valueOf(o, (Class<? extends Number>) type, true)); assertEquals("\"" + o + "\": typeEquals: " + type, ClassUtils.primitiveToWrapper(expected.getClass()), valueOf(o, (Class<? extends Number>) type, true).getClass()); o = "Infinity"; if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) { expected = wrapper.getField("POSITIVE_INFINITY").get(null); } else if (ClassUtils.isPrimitiveWrapper(wrapper)) { expected = wrapper.getField("MAX_VALUE").get(null); } else { expected = BigInteger.class.equals(type) ? INFINITY_DOUBLE.toBigInteger() : INFINITY_DOUBLE; } assertEquals("\"" + o + "\": " + type.getSimpleName(), expected, valueOf(o, (Class<? extends Number>) type, false)); assertEquals("\"" + o + "\": " + type.getSimpleName(), expected, valueOf(o, (Class<? extends Number>) type, true)); assertEquals("\"" + o + "\": typeEquals: " + type, ClassUtils.primitiveToWrapper(expected.getClass()), valueOf(o, (Class<? extends Number>) type, true).getClass()); o = "-Infinity"; if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) { expected = wrapper.getField("NEGATIVE_INFINITY").get(null); } else if (ClassUtils.isPrimitiveWrapper(wrapper)) { expected = wrapper.getField("MIN_VALUE").get(null); } else { expected = BigInteger.class.equals(type) ? INFINITY_DOUBLE.toBigInteger().negate() : INFINITY_DOUBLE.negate(); } assertEquals("\"" + o + "\": " + type.getSimpleName(), expected, valueOf(o, (Class<? extends Number>) type, false)); assertEquals("\"" + o + "\": " + type.getSimpleName(), expected, valueOf(o, (Class<? extends Number>) type, true)); assertEquals("\"" + o + "\": typeEquals: " + type, ClassUtils.primitiveToWrapper(expected.getClass()), valueOf(o, (Class<? extends Number>) type, true).getClass()); } } catch (Exception e) { e.printStackTrace(); fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace())); } }
From source file:com.nginious.http.serialize.JsonDeserializerCreator.java
/** * Creates a JSON deserializer for the specified bean class unless a deserializer has already * been created. Created deserializers are cached and returned on subsequent calls to this method. * /*from w w w . j ava2s .c o m*/ * @param <T> class type for bean * @param beanClazz bean class for which a deserializer should be created * @return the created deserializer * @throws SerializerFactoryException if unable to create deserializer or class is not a bean */ @SuppressWarnings("unchecked") protected <T> JsonDeserializer<T> create(Class<T> beanClazz) throws SerializerFactoryException { JsonDeserializer<T> deserializer = (JsonDeserializer<T>) deserializers.get(beanClazz); if (deserializer != null) { return deserializer; } try { synchronized (this) { deserializer = (JsonDeserializer<T>) deserializers.get(beanClazz); if (deserializer != null) { return deserializer; } checkDeserializability(beanClazz, "json"); String intBeanClazzName = Serialization.createInternalClassName(beanClazz); Method[] methods = beanClazz.getMethods(); String intDeserializerClazzName = new StringBuffer(intBeanClazzName).append("JsonDeserializer") .toString(); // Create class ClassWriter writer = new ClassWriter(0); String signature = Serialization .createClassSignature("com/nginious/http/serialize/JsonDeserializer", intBeanClazzName); writer.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC, intDeserializerClazzName, signature, "com/nginious/http/serialize/JsonDeserializer", null); // Create constructor Serialization.createConstructor(writer, "com/nginious/http/serialize/JsonDeserializer"); // Create deserialize method MethodVisitor visitor = createDeserializeMethod(writer, intBeanClazzName); for (Method method : methods) { Serializable info = method.getAnnotation(Serializable.class); boolean canDeserialize = info == null || (info != null && info.deserialize() && info.types().indexOf("json") > -1); if (canDeserialize && method.getName().startsWith("set") && method.getReturnType().equals(void.class) && method.getParameterTypes().length == 1) { Class<?>[] parameterTypes = method.getParameterTypes(); Class<?> parameterType = parameterTypes[0]; if (parameterType.isArray()) { Class<?> arrayType = parameterType.getComponentType(); if (arrayType.equals(boolean.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeBooleanArray", "[Z", "[Z", intBeanClazzName, method.getName()); } else if (arrayType.equals(double.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeDoubleArray", "[D", "[D", intBeanClazzName, method.getName()); } else if (arrayType.equals(float.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeFloatArray", "[F", "[F", intBeanClazzName, method.getName()); } else if (arrayType.equals(int.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeIntArray", "[I", "[I", intBeanClazzName, method.getName()); } else if (arrayType.equals(long.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeLongArray", "[J", "[J", intBeanClazzName, method.getName()); } else if (arrayType.equals(short.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeShortArray", "[S", "[S", intBeanClazzName, method.getName()); } else if (arrayType.equals(String.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeStringArray", "[Ljava/lang/String;", "[Ljava/lang/String;", intBeanClazzName, method.getName()); } } else if (parameterType.isPrimitive()) { if (parameterType.equals(boolean.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeBoolean", "Z", "Z", intBeanClazzName, method.getName()); } else if (parameterType.equals(double.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeDouble", "D", "D", intBeanClazzName, method.getName()); } else if (parameterType.equals(float.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeFloat", "F", "F", intBeanClazzName, method.getName()); } else if (parameterType.equals(int.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeInt", "I", "I", intBeanClazzName, method.getName()); } else if (parameterType.equals(long.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeLong", "J", "J", intBeanClazzName, method.getName()); } else if (parameterType.equals(short.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeShort", "S", "S", intBeanClazzName, method.getName()); } } else if (parameterType.equals(Calendar.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeCalendar", "Ljava/util/Calendar;", "Ljava/util/Calendar;", intBeanClazzName, method.getName()); } else if (parameterType.equals(Date.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeDate", "Ljava/util/Date;", "Ljava/util/Date;", intBeanClazzName, method.getName()); } else if (parameterType.equals(String.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeString", "Ljava/lang/String;", "Ljava/lang/String;", intBeanClazzName, method.getName()); } } } visitor.visitVarInsn(Opcodes.ALOAD, 3); visitor.visitInsn(Opcodes.ARETURN); visitor.visitMaxs(5, 4); visitor.visitEnd(); writer.visitEnd(); byte[] clazzBytes = writer.toByteArray(); ClassLoader controllerLoader = null; if (classLoader.hasLoaded(beanClazz)) { controllerLoader = beanClazz.getClassLoader(); } else { controllerLoader = this.classLoader; } Class<?> clazz = Serialization.loadClass(controllerLoader, intDeserializerClazzName.replace('/', '.'), clazzBytes); deserializer = (JsonDeserializer<T>) clazz.newInstance(); deserializers.put(beanClazz, deserializer); return deserializer; } } catch (IllegalAccessException e) { throw new SerializerFactoryException(e); } catch (InstantiationException e) { throw new SerializerFactoryException(e); } }