public void testAsConverter_isAView() throws Exception { BiMap<String, Integer> biMap = HashBiMap.create(); biMap.put("one", 1); biMap.put("two", 2); Converter<String, Integer> converter = Maps.asConverter(biMap); assertSame(1, converter.convert("one")); assertSame(2, converter.convert("two")); try { converter.convert("three"); fail(); } catch (IllegalArgumentException expected) { } biMap.put("three", 3); assertSame(1, converter.convert("one")); assertSame(2, converter.convert("two")); assertSame(3, converter.convert("three")); }
/** * Determine the converter with the field type * @param field the field * @return the Converter */ public static Converter<String, ?> determine(Field field) { Class clazz = field.getType(); // Primitive type Converter<String, ?> converter = determinePrimitiveConverter(clazz); if (converter != null){ return converter; } // List or Set or Map if (List.class.equals(clazz) || Map.class.equals(clazz) || Set.class.equals(clazz)){ return determineCollectionConverter((ParameterizedType)field.getGenericType()); } // Common Json Object return new JsonConverter(clazz); }
/** * Determine the converter with the object * @param genericObj the generic object * @return the Converter */ public static Converter<String, ?> determine(Object genericObj) { Type type = ((ParameterizedType)genericObj.getClass().getGenericInterfaces()[0]).getActualTypeArguments()[0]; // Primitive type Converter<String, ?> converter = determinePrimitiveConverter(type); if (converter != null){ return converter; } // List or Set or Map if (type instanceof ParameterizedType){ return determineCollectionConverter((ParameterizedType)type); } // Common json object return new JsonConverter((Class<?>)type); }
/** * Determine the primitive type's converter * @param type the primitive type * @return the primitive type's converter or null */ public static Converter<String, ?> determinePrimitiveConverter(Type type){ if (String.class.equals(type)){ return StringConverter.INSTANCE; } else if (Boolean.class.equals(type) || boolean.class.equals(type)){ return BooleanConverter.INSTANCE; } else if (Integer.class.equals(type) || int.class.equals(type)){ return Ints.stringConverter(); } else if (Long.class.equals(type) || long.class.equals(type)) { return Longs.stringConverter(); } else if (Short.class.equals(type) || short.class.equals(type)){ return Shorts.stringConverter(); } else if (Float.class.equals(type) || float.class.equals(type)){ return Floats.stringConverter(); } else if (Double.class.equals(type) || double.class.equals(type)){ return Doubles.stringConverter(); } return null; }
@Override public <T> T get(final PropertyId<T> propertyId) { Preconditions.checkNotNull(propertyId); Pair<Converter<String, T>, Supplier<T>> information = getRegistrationInformation(propertyId); T value = information.getValue0().convert(getAsStringUnsafe(propertyId)); if (value == null) { T defaultValue = information.getValue1().get(); if (defaultValue != null) { value = defaultValue; LOGGER.debug(String.format("Property '%1s' has no value, fallback on default value.", propertyId)); } else { LOGGER.info(String.format("Property '%1s' has no value and default value is undefined.", propertyId)); } } return value; }
@Override public <T> String getAsString(final PropertyId<T> propertyId) { Pair<Converter<String, T>, Supplier<T>> information = getRegistrationInformation(propertyId); String valueAsString = getAsStringUnsafe(propertyId); if (valueAsString == null) { T defaultValue = information.getValue1().get(); if (defaultValue != null) { valueAsString = information.getValue0().reverse().convert(defaultValue); LOGGER.debug(String.format("Property '%1s' has no value, fallback on default value.", propertyId)); } else { LOGGER.info(String.format("Property '%1s' has no value and default value is undefined.", propertyId)); } } return valueAsString; }
private <T> Reflecter<T> buildReflecter(final Reflecter<T> ref) { addJsonExchangeFunc(ref).autoExchange(); if (jsoner.isPresent() && !jsoner.get().typeConverts.isEmpty()) { ref.fieldLoop(new Decisional<Field>() { @Override protected void decision(Field input) { Class<?> type = input.getType(); Converter<?, ?> converter = jsoner.get().getTypeConverter(type); if (null != converter) { ref.exchange(converter, input.getName()); } } }); } if (!this.mappingFuncs.isEmpty()) { ref.setExchangeFuncs(this.mappingFuncs); } return ref; }
private void assignFieldValue(Object instance, Field field, String cellValue) throws Exception { Object fieldValue = null; if (field.getType().equals(String.class)) { fieldValue = cellValue; } else { Converter<String, ?> converter = getConverter(field); if (converter == null) { throw new Exception(String.format("No converter found for field : s%' with type :'s%'", field.getName(), field.getType().getSimpleName())); } fieldValue = converter.convert(cellValue); } field.set(instance, fieldValue); }
private <F, T> Converter<F, T> defaultConverter( final TypeToken<F> convertFromType, final TypeToken<T> convertToType) { return new Converter<F, T>() { @Override protected T doForward(F a) { return doConvert(convertToType); } @Override protected F doBackward(T b) { return doConvert(convertFromType); } private /*static*/ <S> S doConvert(TypeToken<S> type) { return checkNotNull(getDefaultValue(type)); } }; }
/** * Method stringConverter. * @param enumClass Class<E> * @param or E * @return Converter<String,E> */ public static <E extends Enum<E>> Converter<String,E> stringConverter( final Class<E> enumClass, final E or) { return new Converter<String,E>() { @Override protected String doBackward(E e) { return checkNotNull(e).name(); } @Override protected E doForward(String s) { return getIfPresent(enumClass, s).or(or); } }; }
/** * Method toLowerConverter. * @param locale Locale * @return Converter<String,String> */ public static Converter<String,String> toLowerConverter(final Locale locale) { return new Converter<String,String>() { @Override protected String doForward(String a) { return a.toLowerCase(locale); } @Override protected String doBackward(String b) { return b.toUpperCase(locale); } }; }
@Test public void maps_converter () { BiMap<String, String> stateCapitals = HashBiMap.create(); stateCapitals.put("Wisconsin", "Madison"); stateCapitals.put("Iowa", "Des Moines"); stateCapitals.put("Minnesota", "Saint Paul"); stateCapitals.put("Illinois", "Springfield"); stateCapitals.put("Michigan", "Lansing"); Converter<String, String> converter = Maps.asConverter(stateCapitals); String state = converter.reverse().convert("Madison"); assertEquals("Wisconsin", state); }
/** * Create a prefix {@link Converter} for {@link XPathExpressionException} defined in a particular YANG * {@link Module} .Instantiation requires establishing how a module's imports are mapped to actual modules * and their namespaces. This information is cached and used for improved lookups. * * @param ctx A SchemaContext * @param module Module in which the XPath is defined * @return A new Converter */ public static @Nonnull Converter<String, QNameModule> create(final SchemaContext ctx, final Module module) { // Always check for null ctx requireNonNull(ctx, "Schema context may not be null"); // Use immutable map builder for detection of duplicates (which should never occur) final Builder<String, QNameModule> b = ImmutableBiMap.builder(); b.put(module.getPrefix(), module.getQNameModule()); for (ModuleImport i : module.getImports()) { final Optional<Module> mod = ctx.findModule(i.getModuleName(), i.getRevision()); checkArgument(mod.isPresent(), "Unsatisfied import of %s by module %s", i, module); b.put(i.getPrefix(), mod.get().getQNameModule()); } return Maps.asConverter(b.build()); }
static JaxenXPath create(final Converter<String, QNameModule> converter, final SchemaPath schemaPath, final String xpath) throws JaxenException { final BaseXPath compiled = new BaseXPath(xpath) { private static final long serialVersionUID = 1L; @Override protected ContextSupport getContextSupport() { throw new UnsupportedOperationException(xpath); } }; final Expr expr = compiled.getRootExpr(); LOG.debug("Compiled {} to expression {}", xpath, expr); new ExprWalker(new ExprListener() { // FIXME: perform expression introspection to understand things like apex, etc. }).walk(expr); return new JaxenXPath(converter, schemaPath, compiled); }
@Test public void testIsMemberOfRelationToExternalResource() throws RepositoryException { when(mockContainer.hasType(LDP_DIRECT_CONTAINER)).thenReturn(true); when(mockContainer.hasProperty(LDP_IS_MEMBER_OF_RELATION)).thenReturn(true); when(mockContainer.hasProperty(LDP_MEMBER_RESOURCE)).thenReturn(true); when(mockContainerNode.getProperty(LDP_IS_MEMBER_OF_RELATION)).thenReturn(mockRelationProperty); when(mockContainerNode.getProperty(LDP_MEMBER_RESOURCE)).thenReturn(mockMembershipProperty); when(mockMembershipProperty.getType()).thenReturn(URI); when(mockMembershipProperty.getString()).thenReturn("some:resource"); final String property = "some:uri"; when(mockRelationProperty.getString()).thenReturn(property); testObj = new LdpIsMemberOfRdfContext(mockResource, subjects); final Model model = testObj.collect(toModel()); final Converter<FedoraResource, Resource> nodeSubjects = subjects.reverse(); assertTrue("Expected stream to contain triple", model.contains(nodeSubjects.convert(mockResource), createProperty(property), createResource("some:resource"))); }
@Test public void testIsMemberOfRelationForBinary() throws RepositoryException { when(mockContainer.hasType(LDP_DIRECT_CONTAINER)).thenReturn(true); when(mockContainer.hasProperty(LDP_IS_MEMBER_OF_RELATION)).thenReturn(true); when(mockContainer.hasProperty(LDP_MEMBER_RESOURCE)).thenReturn(true); when(mockContainerNode.getProperty(LDP_IS_MEMBER_OF_RELATION)).thenReturn(mockRelationProperty); when(mockContainerNode.getProperty(LDP_MEMBER_RESOURCE)).thenReturn(mockMembershipProperty); when(mockMembershipProperty.getType()).thenReturn(REFERENCE); when(mockMembershipProperty.getNode()).thenReturn(mockNode); final String property = "some:uri"; when(mockRelationProperty.getString()).thenReturn(property); testObj = new LdpIsMemberOfRdfContext(mockBinary, subjects); final Model model = testObj.collect(toModel()); final Converter<FedoraResource, Resource> nodeSubjects = subjects.reverse(); assertTrue("Expected stream to contain triple", model.contains(nodeSubjects.convert(mockBinary), createProperty(property), nodeToResource(subjects).convert(mockNode))); }
private <T> T getDefaultValue(TypeToken<T> type) { // We assume that all defaults are generics-safe, even if they aren't, // we take the risk. @SuppressWarnings("unchecked") T defaultValue = (T) defaults.getInstance(type.getRawType()); if (defaultValue != null) { return defaultValue; } @SuppressWarnings("unchecked") // All arbitrary instances are generics-safe T arbitrary = (T) ArbitraryInstances.get(type.getRawType()); if (arbitrary != null) { return arbitrary; } if (type.getRawType() == Class.class) { // If parameter is Class<? extends Foo>, we return Foo.class @SuppressWarnings("unchecked") T defaultClass = (T) getFirstTypeParameter(type.getType()).getRawType(); return defaultClass; } if (type.getRawType() == TypeToken.class) { // If parameter is TypeToken<? extends Foo>, we return TypeToken<Foo>. @SuppressWarnings("unchecked") T defaultType = (T) getFirstTypeParameter(type.getType()); return defaultType; } if (type.getRawType() == Converter.class) { TypeToken<?> convertFromType = type.resolveType( Converter.class.getTypeParameters()[0]); TypeToken<?> convertToType = type.resolveType( Converter.class.getTypeParameters()[1]); @SuppressWarnings("unchecked") // returns default for both F and T T defaultConverter = (T) defaultConverter(convertFromType, convertToType); return defaultConverter; } if (type.getRawType().isInterface()) { return newDefaultReturningProxy(type); } return null; }
void check() { runTester(); @SuppressWarnings("unchecked") // We are checking it anyway Converter<String, Integer> defaultConverter = (Converter<String, Integer>) getDefaultParameterValue(0); assertEquals(Integer.valueOf(0), defaultConverter.convert("anything")); assertEquals("", defaultConverter.reverse().convert(123)); assertNull(defaultConverter.convert(null)); assertNull(defaultConverter.reverse().convert(null)); }
public void testAsConverter_nominal() throws Exception { ImmutableBiMap<String, Integer> biMap = ImmutableBiMap.of( "one", 1, "two", 2); Converter<String, Integer> converter = Maps.asConverter(biMap); for (Entry<String, Integer> entry : biMap.entrySet()) { assertSame(entry.getValue(), converter.convert(entry.getKey())); } }
public void testAsConverter_inverse() throws Exception { ImmutableBiMap<String, Integer> biMap = ImmutableBiMap.of( "one", 1, "two", 2); Converter<String, Integer> converter = Maps.asConverter(biMap); for (Entry<String, Integer> entry : biMap.entrySet()) { assertSame(entry.getKey(), converter.reverse().convert(entry.getValue())); } }
public void testAsConverter_noMapping() throws Exception { ImmutableBiMap<String, Integer> biMap = ImmutableBiMap.of( "one", 1, "two", 2); Converter<String, Integer> converter = Maps.asConverter(biMap); try { converter.convert("three"); fail(); } catch (IllegalArgumentException expected) { } }
public void testAsConverter_nullConversions() throws Exception { ImmutableBiMap<String, Integer> biMap = ImmutableBiMap.of( "one", 1, "two", 2); Converter<String, Integer> converter = Maps.asConverter(biMap); assertNull(converter.convert(null)); assertNull(converter.reverse().convert(null)); }
public void testAsConverter_toString() { ImmutableBiMap<String, Integer> biMap = ImmutableBiMap.of( "one", 1, "two", 2); Converter<String, Integer> converter = Maps.asConverter(biMap); assertEquals("Maps.asConverter({one=1, two=2})", converter.toString()); }
public void testAsConverter_serialization() { ImmutableBiMap<String, Integer> biMap = ImmutableBiMap.of( "one", 1, "two", 2); Converter<String, Integer> converter = Maps.asConverter(biMap); SerializableTester.reserializeAndAssert(converter); }
@GwtIncompatible // Float.toString returns different value in GWT. public void testStringConverter_convert() { Converter<String, Float> converter = Floats.stringConverter(); assertEquals((Float) 1.0f, converter.convert("1.0")); assertEquals((Float) 0.0f, converter.convert("0.0")); assertEquals((Float) (-1.0f), converter.convert("-1.0")); assertEquals((Float) 1.0f, converter.convert("1")); assertEquals((Float) 0.0f, converter.convert("0")); assertEquals((Float) (-1.0f), converter.convert("-1")); assertEquals((Float) 1e6f, converter.convert("1e6")); assertEquals((Float) 1e-6f, converter.convert("1e-6")); }
@GwtIncompatible // Float.toString returns different value in GWT. public void testStringConverter_reverse() { Converter<String, Float> converter = Floats.stringConverter(); assertEquals("1.0", converter.reverse().convert(1.0f)); assertEquals("0.0", converter.reverse().convert(0.0f)); assertEquals("-1.0", converter.reverse().convert(-1.0f)); assertEquals("1000000.0", converter.reverse().convert(1e6f)); assertEquals("1.0E-6", converter.reverse().convert(1e-6f)); }
public void testStringConverter_convert() { Converter<String, Double> converter = Doubles.stringConverter(); assertEquals((Double) 1.0, converter.convert("1.0")); assertEquals((Double) 0.0, converter.convert("0.0")); assertEquals((Double) (-1.0), converter.convert("-1.0")); assertEquals((Double) 1.0, converter.convert("1")); assertEquals((Double) 0.0, converter.convert("0")); assertEquals((Double) (-1.0), converter.convert("-1")); assertEquals((Double) 1e6, converter.convert("1e6")); assertEquals((Double) 1e-6, converter.convert("1e-6")); }
@GwtIncompatible // Double.toString returns different value in GWT. public void testStringConverter_reverse() { Converter<String, Double> converter = Doubles.stringConverter(); assertEquals("1.0", converter.reverse().convert(1.0)); assertEquals("0.0", converter.reverse().convert(0.0)); assertEquals("-1.0", converter.reverse().convert(-1.0)); assertEquals("1000000.0", converter.reverse().convert(1e6)); assertEquals("1.0E-6", converter.reverse().convert(1e-6)); }
public void testStringConverter_convert() { Converter<String, Short> converter = Shorts.stringConverter(); assertEquals((Short) (short) 1, converter.convert("1")); assertEquals((Short) (short) 0, converter.convert("0")); assertEquals((Short) (short) (-1), converter.convert("-1")); assertEquals((Short) (short) 255, converter.convert("0xff")); assertEquals((Short) (short) 255, converter.convert("0xFF")); assertEquals((Short) (short) (-255), converter.convert("-0xFF")); assertEquals((Short) (short) 255, converter.convert("#0000FF")); assertEquals((Short) (short) 438, converter.convert("0666")); }
public void testStringConverter_reverse() { Converter<String, Short> converter = Shorts.stringConverter(); assertEquals("1", converter.reverse().convert((short) 1)); assertEquals("0", converter.reverse().convert((short) 0)); assertEquals("-1", converter.reverse().convert((short) -1)); assertEquals("255", converter.reverse().convert((short) 0xff)); assertEquals("255", converter.reverse().convert((short) 0xFF)); assertEquals("-255", converter.reverse().convert((short) -0xFF)); assertEquals("438", converter.reverse().convert((short) 0666)); }
public void testStringConverter_convert() { Converter<String, Long> converter = Longs.stringConverter(); assertEquals((Long) 1L, converter.convert("1")); assertEquals((Long) 0L, converter.convert("0")); assertEquals((Long) (-1L), converter.convert("-1")); assertEquals((Long) 255L, converter.convert("0xff")); assertEquals((Long) 255L, converter.convert("0xFF")); assertEquals((Long) (-255L), converter.convert("-0xFF")); assertEquals((Long) 255L, converter.convert("#0000FF")); assertEquals((Long) 438L, converter.convert("0666")); }
public void testStringConverter_reverse() { Converter<String, Long> converter = Longs.stringConverter(); assertEquals("1", converter.reverse().convert(1L)); assertEquals("0", converter.reverse().convert(0L)); assertEquals("-1", converter.reverse().convert(-1L)); assertEquals("255", converter.reverse().convert(0xffL)); assertEquals("255", converter.reverse().convert(0xFFL)); assertEquals("-255", converter.reverse().convert(-0xFFL)); assertEquals("438", converter.reverse().convert(0666L)); }