@Test(expected = ConversionException.class) public void enumConverterWillThrowAnExceptionIfGivenAnInvalidOrdinal() throws Exception { final TypeConverter<Object> instantiator = new EnumConverter(); final Target<Object> target = new Target<>(Stooges.class, "foo"); final String overNineThousand = "9001"; instantiator.instantiate(target, new Parameters(new Parameter("foo", overNineThousand))); }
@Test public void functionalInterface() throws Exception { // TypeConverter<String, Integer> converter = (from) -> Integer.valueOf(from); // Case 1 TypeConverter<String, Integer> converter = Integer::valueOf; // Case 2 final Integer v = converter.convert("123"); assert v == 123; }
@Test public void testToNullDefaultValue() throws Exception { config.setNullFillerChar((char) 0); config.setDefaultValue("42"); typeConverter.initialize(config); assertEquals(42, (long) typeConverter.to(new byte[4], 0, 2, 2, true)); }
/** * Removes the type converter. * * @param tc */ public void removeConverter(TypeConverter tc) { if (tc.getSupportedTypes() == null) untypedTypeEncoders.remove(tc); else for (List<TypeConverter> tcList : tcMap.values()) if (tcList.contains(tc)) tcList.remove(tc); registeredConverterClasses.remove(tc.getClass()); }
@Test public void enumConverterCanConvertOrdinals() { final TypeConverter<Object> instantiator = new EnumConverter(); final Target<Object> target = new Target<>(Stooges.class, "foo"); final Stooges object = (Stooges) instantiator.instantiate(target, new Parameters(new Parameter("foo", "1"))); assertEquals(Stooges.CURLY, object); }
@Test public void testToNullValue() throws Exception { expectedEx.expect(NumberFormatException.class); expectedEx.expectMessage("For input string"); config.setNullFillerChar((char) 0); typeConverter.initialize(config); assertEquals(null, typeConverter.to(new byte[4], 0, 2, 2, true)); }
@Test public void enumConverterCanConvertLiterals() throws Exception { final TypeConverter<Object> instantiator = new EnumConverter(); final Target<Object> target = new Target<>(Stooges.class, "foo"); assertTrue(instantiator.isAbleToInstantiate(target)); final Stooges object = (Stooges) instantiator.instantiate(target, new Parameters(new Parameter("foo", "CURLY"))); assertEquals(Stooges.CURLY, object); }
/** * Add a type converter. If it is a duplicate for an existing type, it will override that type. * * @param tc */ public TypeConverter addConverter(TypeConverter tc) { if (tc.getSupportedTypes() != null) for (Class c : tc.getSupportedTypes()) addTypedConverter(c, tc); else untypedTypeEncoders.add(tc); tc.setMapper(mapr); registeredConverterClasses.add(tc.getClass()); return tc; }
protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { Object result, root = context.getRoot(); int count = jjtGetNumChildren(); Object[] args = OgnlRuntime.getObjectArrayPool().create(count); try { for (int i = 0; i < count; ++i) { args[i] = _children[i].getValue(context, root); } if (isArray) { if (args.length == 1) { try { Class componentClass = OgnlRuntime.classForName(context, className); List sourceList = null; int size; if (args[0] instanceof List) { sourceList = (List) args[0]; size = sourceList.size(); } else { size = (int) OgnlOps.longValue(args[0]); } result = Array.newInstance(componentClass, size); if (sourceList != null) { TypeConverter converter = context.getTypeConverter(); for (int i = 0, icount = sourceList.size(); i < icount; i++) { Object o = sourceList.get(i); if ((o == null) || componentClass.isInstance(o)) { Array.set(result, i, o); } else { Array.set( result, i, converter.convertValue(context, null, null, null, o, componentClass)); } } } } catch (ClassNotFoundException ex) { throw new OgnlException("array component class '" + className + "' not found", ex); } } else { throw new OgnlException("only expect array size or fixed initializer list"); } } else { result = OgnlRuntime.callConstructor(context, className, args); } return result; } finally { OgnlRuntime.getObjectArrayPool().recycle(args); } }
private static Ratings getRatings(Element e) { if (e == null) { return null; } Ratings r = new Ratings(); r.setAvg(DOUBLE.safeValue(e.getChildText("avg"))); r.setVotes(INTEGER.safeValue(e.getChildText("votes"))); r.setHistory(new HashMap<String, Integer>()); populateMap(r.getHistory(), e.getChild("history")); return r; }
private TypeConverter getEncoder(final Class c) { List<TypeConverter> tcs = tcMap.get(c); if (tcs != null) { if (tcs.size() > 1) log.warning("Duplicate converter for " + c + ", returning first one from " + tcs); return tcs.get(0); } for (TypeConverter tc : untypedTypeEncoders) if (tc.canHandle(c)) return tc; throw new ConverterNotFoundException("Cannot find encoder for " + c.getName()); }
public void toDBObject( final Object containingObject, final MappedField mf, final DBObject dbObj, MapperOptions opts) { Object fieldValue = mf.getFieldValue(containingObject); TypeConverter enc = getEncoder(fieldValue, mf); Object encoded = enc.encode(fieldValue, mf); if (encoded != null || opts.storeNulls) { dbObj.put(mf.getNameToStore(), encoded); } }
@Test public void lambdaScope() throws Exception { final int num1 = 1; // final TypeConverter<String, Integer> converter = (f) -> Integer.valueOf(f) + num1; final Integer r1 = converter.convert("5"); assert r1 == 6; final int num2 = 1; // implicit final TypeConverter<String, Integer> converter2 = (f) -> Integer.valueOf(f) + num2; final Integer r2 = converter2.convert("5"); assert r2 == 6; // num2 += 2; compile error }
@Test public void testConvertNull() throws Exception { SyntheticField field = mock(SyntheticField.class); when(field.getType()).thenReturn((Class) SimpleBaseDomain.class); String[] tags = new String[] {"a", "b", "c"}; assertThat(typeConverter.convert(null, field, null, tags)).isNull(); }
/** Get converted value and original value of this Binding. */ private Object[] getAttributeValues(Component comp) { if (!isSavable() || _attr.startsWith("_") || DataBinder.isTemplate(comp) || comp.getPage() == null) { return null; // cannot save, a control attribute, or a detached component, skip! } Object rawval = null; try { rawval = Fields.get(comp, _attr); } catch (NoSuchMethodException ex) { // Bug #1813278, Annotations do not work with xhtml tags if (comp instanceof DynamicPropertied) { final DynamicPropertied dpcomp = (DynamicPropertied) comp; if (dpcomp.hasDynamicProperty(_attr)) { rawval = dpcomp.getDynamicProperty(_attr); } else { throw UiException.Aide.wrap(ex); } } else if (comp.getAttributes() .containsKey( _attr)) { // Feature #2855116. Get value from component custom-attribute(also a // variable in ZK5). rawval = comp.getAttribute(_attr); } else { throw UiException.Aide.wrap(ex); } } try { final Object val = (_converter == null) ? rawval : _converter.coerceToBean(rawval, comp); return val == TypeConverter.IGNORE ? null : new Object[] {val, rawval}; } catch (ClassCastException ex) { throw UiException.Aide.wrap(ex); } }
@Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); typeConverter = new IntegerToLong(); typeConverter.initialize(config); }
@Test public void testConvert() throws Exception { SimpleBaseTo source = new SimpleBaseTo(); SyntheticField field = mock(SyntheticField.class); when(field.getType()).thenReturn((Class) SimpleBaseDomain.class); String[] tags = new String[] {"a", "b", "c"}; typeConverter.convert(source, field, null, tags); verify(jTransfo).convertTo(source, SimpleBaseDomain.class, tags); }
public void fromDBObject(final DBObject dbObj, final MappedField mf, final Object targetEntity) { Object object = mf.getDbObjectValue(dbObj); if (object == null) { processMissingField(mf); } else { TypeConverter enc = getEncoder(mf); Object decodedValue = enc.decode(mf.getType(), object, mf); try { mf.setFieldValue(targetEntity, decodedValue); } catch (IllegalArgumentException e) { throw new MappingException( "Error setting value from converter (" + enc.getClass().getSimpleName() + ") for " + mf.getFullName() + " to " + decodedValue); } } }
/** Convert para to special type and keep it */ public Controller keepPara(Class type, String name) { String[] values = request.getParameterValues(name); if (values != null) { if (values.length == 1) try { request.setAttribute(name, TypeConverter.convert(type, values[0])); } catch (ParseException e) { } else request.setAttribute(name, values); } return this; }
@Test public void testReverse() throws Exception { SimpleBaseDomain source = new SimpleBaseDomain(); SimpleBaseTo target = new SimpleBaseTo(); when(reflectionHelper.newInstance(any(Class.class))).thenReturn(target); SyntheticField field = mock(SyntheticField.class); when(field.getType()).thenReturn((Class) SimpleBaseTo.class); String[] tags = new String[] {"a", "b", "c"}; typeConverter.reverse(source, field, null, tags); verify(jTransfo).convert(source, target, tags); }
private TypeConverter getEncoder(Object val, MappedField mf) { List<TypeConverter> tcs = null; if (val != null) tcs = tcMap.get(val.getClass()); if (tcs == null || (tcs.size() > 0 && tcs.get(0) instanceof PassthroughConverter)) tcs = tcMap.get(mf.getType()); if (tcs != null) { if (tcs.size() > 1) log.warning( "Duplicate converter for " + mf.getType() + ", returning first one from " + tcs); return tcs.get(0); } for (TypeConverter tc : untypedTypeEncoders) if (tc.canHandle(mf) || (val != null && tc.isSupported(val.getClass(), mf))) return tc; throw new ConverterNotFoundException( "Cannot find encoder for " + mf.getType() + " as need for " + mf.getFullName()); }
@Test public void testReverseIllegalAccessException() throws Exception { SimpleBaseDomain source = new SimpleBaseDomain(); SimpleBaseTo target = new SimpleBaseTo(); when(reflectionHelper.newInstance(any(Class.class))).thenThrow(new IllegalAccessException()); SyntheticField field = mock(SyntheticField.class); when(field.getType()).thenReturn((Class) SimpleBaseTo.class); exception.expect(JTransfoException.class); exception.expectMessage( "Cannot create instance of transfer object class org.jtransfo.object.SimpleBaseTo."); typeConverter.reverse(source, field, null); }
public static Drop extractDrop(Document doc) { Drop d = new Drop(); Element iq = doc.getRootElement(); Element drop = iq.getChild("drop"); d.setId(drop.getChildText("id")); d.setCreatorId(drop.getChildText("creatorId")); d.setCreationDate(DATE.safeValue(drop.getChildText("creationDate"))); d.setLastEditorId(drop.getChildText("lastEditorId")); d.setLastEditDate(DATE.safeValue(drop.getChildText("lastEditDate"))); d.setVersion(INTEGER.safeValue(drop.getChildText("version"))); d.setPath(drop.getChildText("path")); d.setFlowId(drop.getChildText("flowId")); d.setParentDropId(drop.getChildText("parentDropId")); d.setFhash(drop.getChildText("fhash")); d.setActions(new HashMap<String, Boolean>()); populateMap(d.getActions(), drop.getChild("actions")); d.setCreator(new HashMap<String, String>()); populateMap(d.getCreator(), drop.getChild("creator")); d.setFlags(new HashMap<String, Integer>()); populateMap(d.getFlags(), drop.getChild("flags")); d.setRatings(getRatings(drop.getChild("ratings"))); d.setElems(getElements(drop.getChild("elems"))); return d; }
@Test public void testCanConvert() throws Exception { assertThat(typeConverter.canConvert(String.class, String.class)).isFalse(); assertThat(typeConverter.canConvert(SimpleBaseTo.class, SimpleBaseDomain.class)).isTrue(); assertThat(typeConverter.canConvert(SimpleBaseTo.class, String.class)).isFalse(); assertThat(typeConverter.canConvert(SimpleBaseTo.class, SimpleExtendedDomain.class)).isFalse(); assertThat(typeConverter.canConvert(SimpleExtendedTo.class, SimpleExtendedDomain.class)) .isTrue(); assertThat(typeConverter.canConvert(SimpleExtendedTo.class, SimpleBaseDomain.class)).isTrue(); }
private RexNode handleExplicitCast(ExprNodeGenericFuncDesc func, List<RexNode> childRexNodeLst) throws CalciteSemanticException { RexNode castExpr = null; if (childRexNodeLst != null && childRexNodeLst.size() == 1) { GenericUDF udf = func.getGenericUDF(); if ((udf instanceof GenericUDFToChar) || (udf instanceof GenericUDFToVarchar) || (udf instanceof GenericUDFToDecimal) || (udf instanceof GenericUDFToDate) || (udf instanceof GenericUDFToBinary) || castExprUsingUDFBridge(udf)) { castExpr = cluster .getRexBuilder() .makeAbstractCast( TypeConverter.convert(func.getTypeInfo(), cluster.getTypeFactory()), childRexNodeLst.get(0)); } } return castExpr; }
private <T> T convertWith( final TypeConverter<T> instantiator, final Class<T> type, final String stringValue) { final Target<T> target = Target.create(type, "foo"); assertTrue(instantiator.isAbleToInstantiate(target)); return instantiator.instantiate(target, new Parameters(new Parameter("foo", stringValue))); }
@Test(expected = ConversionException.class) public void enumConverterWillThrowAnExceptionIfGivenANonEnumClass() throws Exception { final TypeConverter<Object> instantiator = new EnumConverter(); final Target<Object> target = new Target<>(String.class, "foo"); instantiator.instantiate(target, new Parameters(new Parameter("foo", "baz"))); }
@Test(expected = ConversionException.class) public void enumConverterWillThrowAnExceptionIfGivenAnUnrecognizedString() throws Exception { final TypeConverter<Object> instantiator = new EnumConverter(); final Target<Object> target = new Target<>(Stooges.class, "foo"); instantiator.instantiate(target, new Parameters(new Parameter("foo", "LAUREL"))); }
@Test public void testFrom() throws Exception { byte[] bytes = typeConverter.from(12147483648L, 11, -1, true); assertArrayEquals("12147483648".getBytes(StandardCharsets.UTF_8), bytes); }
@Test public void testFromOverflow() throws Exception { expectedEx.expect(TypeConverterException.class); expectedEx.expectMessage("Field to small for value"); byte[] bytes = typeConverter.from(12147483648L, 4, -1, true); }