下面列出了怎么用com.google.common.base.Converter的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Gets the first value from the primary (nullable) or backup (optional) FieldOrValue
* instances, extracts non-empty values, and passes them to the given ItemMetadata setter.
*
* @param <T> the field type in this class
* @param <M> the field type in the API model, usually String
* @param primary the FieldOrValue from the setter
* @param backup the FieldOrValue from the configuration
* @param values the multimap used to resolve field name references
* @param converter the converter for multimap values
* @param isEmpty a predicate to check whether a value is present or missing
*/
private static <T, M> void setFromFieldOrValues(FieldOrValue<T> primary,
Optional<FieldOrValue<T>> backup,
Multimap<String, Object> values,
Converter<Object, T> converter,
Predicate<T> isEmpty,
Function<T, M> extractor,
Consumer<M> setter) {
T value = getSingleValue(primary, values, converter);
if (isEmpty.test(value) && backup.isPresent()) {
value = getSingleValue(backup.get(), values, converter);
}
if (!isEmpty.test(value)) {
setter.accept(extractor.apply(value));
}
}
private static <T> T getSingleValue(
FieldOrValue<T> field,
Multimap<String, Object> values,
Converter<Object, T> converter) {
if (field == null) {
return null;
}
if (field.fieldName == null) {
return field.defaultValue;
}
List<Object> fieldValues =
values.get(field.fieldName).stream().filter(Objects::nonNull).collect(Collectors.toList());
if (fieldValues.isEmpty()) {
return field.defaultValue;
}
return converter.convert(fieldValues.get(0));
}
@Test
public void dateConverter_fromDateTime() throws IOException {
setupConfig.initConfig(new Properties());
when(mockIndexingService.getSchema()).thenReturn(new Schema());
StructuredData.initFromConfiguration(mockIndexingService);
Date expected = new Date().setYear(2018).setMonth(8).setDay(8);
Converter<Object, Date> converter = StructuredData.DATE_CONVERTER;
for (String dateString : new String[] {
// API Date class doesn't have a time zone, so anything will match.
"2018-08-08T23:48:17-11:00", // 2018-08-09 in most local time zones.
"2018-08-08T00:01:00+14:00", // 2018-08-07 in most local time zones.
"2018-08-08",
}) {
try {
collector.checkThat(dateString, converter.convert(new DateTime(dateString)),
equalTo(expected));
} catch (NumberFormatException e) {
collector.addError(e);
}
}
}
/**
* Generate URI for method.
*
* @param schema
* the schema
* @param listFieldAlias
* the list field alias
* @param alreadyUsedName
* the already used name
* @param format
* the format
* @param entry
* the entry
* @param method
* the method
*/
private void generateURIForMethod(SQLiteDatabaseSchema schema, List<FieldSpec> listFieldAlias, Set<String> alreadyUsedName, Converter<String, String> format, Pair<String, ContentEntry> entry,
SQLiteModelMethod method) {
if (method == null)
return;
String alias = "URI_" + entry.value1.pathCostant.substring(0, entry.value1.pathCostant.lastIndexOf("_")).replace("PATH_", "") + "_" + format.convert(method.getName());
if (!alreadyUsedName.contains(alias)) {
String contentUri = schema.contentProviderUri().replace("*", "[*]") + "/" + entry.value1.uriTemplate.replace("*", "[*]");
String contentUriWithParameter = method.contentProviderUri().replace("*", "[*]");
listFieldAlias.add(FieldSpec.builder(Uri.class, alias, Modifier.STATIC, Modifier.FINAL, Modifier.PUBLIC).addJavadoc("<h2>URI standard</h2>\n<pre>$L</pre></p>\n", contentUri)
.addJavadoc("<h2>URI with parameters</h2>\n<pre>$L</pre>\n\n", contentUriWithParameter)
.addJavadoc("<p>Method associated to this URI is {@link $LImpl#$L}</p>\n", method.getParent().getName(), method.contentProviderMethodName)
.initializer(CodeBlock.of("URI_" + entry.value1.pathCostant)).build());
alreadyUsedName.add(alias);
}
}
/**
* Gets the bind mapper name.
*
* @param context the context
* @param typeName the type name
* @return the bind mapper name
*/
public String getBindMapperName(BindTypeContext context, TypeName typeName) {
Converter<String, String> format = CaseFormat.UPPER_CAMEL.converterTo(CaseFormat.LOWER_CAMEL);
TypeName bindMapperName=TypeUtility.mergeTypeNameWithSuffix(typeName,BindTypeBuilder.SUFFIX);
String simpleName=format.convert(TypeUtility.simpleName(bindMapperName));
if (!alreadyGeneratedMethods.contains(simpleName))
{
alreadyGeneratedMethods.add(simpleName);
if (bindMapperName.equals(beanTypeName))
{
context.builder.addField(FieldSpec.builder(bindMapperName, simpleName, modifiers)
.addJavadoc("$T", bindMapperName)
.initializer("this")
.build());
} else {
context.builder.addField(FieldSpec.builder(bindMapperName, simpleName, modifiers)
.addJavadoc("$T", bindMapperName)
.initializer("$T.mapperFor($T.class)", BinderUtils.class, typeName)
.build());
}
}
return simpleName;
}
/**
* 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);
}
};
}
/**
* 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<? extends 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());
}
@Test
public void convert_toRequestProto() {
Converter<RouteLookupRequest, RlsProtoData.RouteLookupRequest> converter =
new RouteLookupRequestConverter();
RouteLookupRequest proto = RouteLookupRequest.newBuilder()
.setServer("server")
.setPath("path")
.setTargetType("target")
.putKeyMap("key1", "val1")
.build();
RlsProtoData.RouteLookupRequest object = converter.convert(proto);
assertThat(object.getServer()).isEqualTo("server");
assertThat(object.getPath()).isEqualTo("path");
assertThat(object.getTargetType()).isEqualTo("target");
assertThat(object.getKeyMap()).containsExactly("key1", "val1");
}
@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);
}
private UniqueCachedNaming(Iterable<T> values) {
Objects.requireNonNull(values, "values");
this.names = buildBiMap(values);
this.converter = new Converter<T, String>() {
@Override
protected String doForward(T toName) {
Preconditions.checkArgument(names.containsKey(toName), "%s was not cached", toName);
return names.get(toName);
}
@Override
protected T doBackward(String fromName) {
Preconditions.checkArgument(names.containsValue(fromName), "name %s not found", fromName);
return names.inverse().get(fromName);
}
};
}
private ValueExtractor(
Converter<Object, T> valueConverter,
NamedPropertyBuilder<T> propertyBuilder,
boolean isRepeated) {
this.valueConverter = valueConverter;
this.propertyBuilder = propertyBuilder;
this.isRepeated = isRepeated;
}
@Test
public void testDateTimeConverter_nonZeroOffset() throws IOException {
setupConfig.initConfig(new Properties());
when(mockIndexingService.getSchema()).thenReturn(new Schema());
StructuredData.initFromConfiguration(mockIndexingService);
String rfc3339String = "2018-08-08T15:48:17.000-07:00";
DateTime expected = new DateTime(rfc3339String);
// Baseline so we don't chase unexpected errors below.
assertEquals("Baseline failure", rfc3339String, expected.toString());
Converter<Object, DateTime> converter = StructuredData.DATETIME_CONVERTER;
for (String dateString : new String[] {
"2018-08-08T15:48:17.000-07:00",
"2018-08-08t15:48:17-07:00", // Lowercase t
// "2018-08-08T15:48:17-07", TODO(jlacey): Restore these if running Java 9.
"2018-08-08 15:48:17.000-07:00",
"2018-08-08 15:48:17-07:00",
// "2018-08-08 15:48:17-07", TODO(jlacey): ibid.
"Wed, 8 Aug 2018 15:48:17 -0700",
"08 AUG 2018 15:48:17 -0700", // Uppercase month name
}) {
try {
collector.checkThat(dateString, converter.convert(dateString), equalTo(expected));
} catch (NumberFormatException e) {
collector.addError(e);
}
}
}
@Test
public void testDateTimeConverter_zeroOffset() throws IOException {
setupConfig.initConfig(new Properties());
when(mockIndexingService.getSchema()).thenReturn(new Schema());
StructuredData.initFromConfiguration(mockIndexingService);
String rfc3339String = "2018-08-08T15:48:17.000Z";
DateTime expected = new DateTime(rfc3339String);
// Baseline so we don't chase unexpected errors below.
assertEquals("Baseline failure", rfc3339String, expected.toString());
Converter<Object, DateTime> converter = StructuredData.DATETIME_CONVERTER;
for (String dateString : new String[] {
"2018-08-08T15:48:17.000-00:00",
"2018-08-08T15:48:17+00:00",
// "2018-08-08T15:48:17+00", TODO(jlacey): ibid.
"2018-08-08T15:48:17Z",
"2018-08-08 15:48:17.000-00:00",
"2018-08-08 15:48:17+00:00",
// "2018-08-08 15:48:17+00", TODO(jlacey): ibid.
"2018-08-08 15:48:17Z",
"Wed, 8 Aug 2018 15:48:17 +0000",
"08 Aug 2018 15:48:17 GMT",
}) {
try {
collector.checkThat(dateString, converter.convert(dateString), equalTo(expected));
} catch (NumberFormatException e) {
collector.addError(e);
}
}
}
@Test
public void testDateTimeConverter_noOffset() throws IOException {
setupConfig.initConfig(new Properties());
when(mockIndexingService.getSchema()).thenReturn(new Schema());
StructuredData.initFromConfiguration(mockIndexingService);
TimeZone original = TimeZone.getDefault();
TimeZone.setDefault(TimeZone.getTimeZone("GMT-04:00"));
try {
String rfc3339String = "2018-08-08T15:48:17.000-04:00";
DateTime expected = new DateTime(rfc3339String);
// Baseline so we don't chase unexpected errors below.
assertEquals("Baseline failure", rfc3339String, expected.toString());
Converter<Object, DateTime> converter = StructuredData.DATETIME_CONVERTER;
for (String dateString : new String[] {
"2018-08-08T15:48:17.000",
"2018-08-08T15:48:17",
"2018-08-08 15:48:17.000",
"2018-08-08 15:48:17",
}) {
try {
collector.checkThat(dateString, converter.convert(dateString), equalTo(expected));
} catch (NumberFormatException e) {
collector.addError(e);
}
}
} finally {
TimeZone.setDefault(original);
}
}
@Test
public void testDateTimeConverter_dateOnly() throws IOException {
setupConfig.initConfig(new Properties());
when(mockIndexingService.getSchema()).thenReturn(new Schema());
StructuredData.initFromConfiguration(mockIndexingService);
TimeZone original = TimeZone.getDefault();
TimeZone.setDefault(TimeZone.getTimeZone("GMT-04:00"));
try {
String rfc3339String = "2018-08-08T00:00:00.000-04:00";
DateTime expected = new DateTime(rfc3339String);
// Baseline so we don't chase unexpected errors below.
assertEquals("Baseline failure", rfc3339String, expected.toString());
Converter<Object, DateTime> converter = StructuredData.DATETIME_CONVERTER;
for (String dateString : new String[] {
"2018-08-08-04:00",
"2018-08-08",
}) {
try {
collector.checkThat(dateString, converter.convert(dateString), equalTo(expected));
} catch (NumberFormatException e) {
collector.addError(e);
}
}
} finally {
TimeZone.setDefault(original);
}
}
@Test
public void testDateTimeConverter_dateOnly_mismatch() throws IOException {
setupConfig.initConfig(new Properties());
when(mockIndexingService.getSchema()).thenReturn(new Schema());
StructuredData.initFromConfiguration(mockIndexingService);
TimeZone original = TimeZone.getDefault();
TimeZone.setDefault(TimeZone.getTimeZone("GMT-04:00"));
try {
String rfc3339String = "2018-08-08T00:00:00.000-04:00";
DateTime expected = new DateTime(rfc3339String);
// Baseline so we don't chase unexpected errors below.
assertEquals("Baseline failure", rfc3339String, expected.toString());
Converter<Object, DateTime> converter = StructuredData.DATETIME_CONVERTER;
for (String dateString : new String[] {
// Time zones are still parsed from strings with no time.
"2018-08-08-07:00",
}) {
try {
collector.checkThat(dateString, converter.convert(dateString), not(equalTo(expected)));
} catch (NumberFormatException e) {
collector.addError(e);
}
}
} finally {
TimeZone.setDefault(original);
}
}
@Test
public void testDateTimeConverter_noDate() throws IOException {
setupConfig.initConfig(new Properties());
when(mockIndexingService.getSchema()).thenReturn(new Schema());
StructuredData.initFromConfiguration(mockIndexingService);
Converter<Object, DateTime> converter = StructuredData.DATETIME_CONVERTER;
thrown.expect(NumberFormatException.class);
converter.convert("15:48:17-04:00");
}
@Test
public void testDateTimeConverter_configuredPatterns() throws IOException {
when(mockIndexingService.getSchema()).thenReturn(new Schema());
Properties config = new Properties();
config.put(StructuredData.DATETIME_PATTERNS, "M/d/yy h:mm:ss a zzz; dd MMM yyyy HH:mm[:ss]xx");
setupConfig.initConfig(config);
StructuredData.initFromConfiguration(mockIndexingService);
String rfc3339String = "2018-08-08T15:48:17.000-07:00";
DateTime expected = new DateTime(rfc3339String);
// Baseline so we don't chase unexpected errors below.
assertEquals("Baseline failure", rfc3339String, expected.toString());
Converter<Object, DateTime> converter = StructuredData.DATETIME_CONVERTER;
for (String dateString : new String[] {
"2018-08-08T15:48:17-07:00",
"Wed, 8 Aug 2018 15:48:17 -0700",
"8/8/18 3:48:17 PM GMT-07:00",
"08 AuG 2018 15:48:17-0700", // Mixed-case month name
}) {
try {
collector.checkThat(dateString, converter.convert(dateString), equalTo(expected));
} catch (NumberFormatException e) {
collector.addError(e);
}
}
}
@Test
public void testDateTimeConverter_configuredPatterns_dateOnly() throws IOException {
when(mockIndexingService.getSchema()).thenReturn(new Schema());
Properties config = new Properties();
config.put(StructuredData.DATETIME_PATTERNS, "M/d/yy ;dd MMM uuuu");
setupConfig.initConfig(config);
StructuredData.initFromConfiguration(mockIndexingService);
TimeZone original = TimeZone.getDefault();
TimeZone.setDefault(TimeZone.getTimeZone("GMT-04:00"));
try {
String rfc3339String = "2018-08-08T00:00:00.000-04:00";
DateTime expected = new DateTime(rfc3339String);
// Baseline so we don't chase unexpected errors below.
assertEquals("Baseline failure", rfc3339String, expected.toString());
Converter<Object, DateTime> converter = StructuredData.DATETIME_CONVERTER;
for (String dateString : new String[] {
"2018-08-08-04:00",
"Wed, 8 Aug 2018 00:00:00 -0400",
"8/8/18",
"08 aUg 2018",
}) {
try {
collector.checkThat(dateString, converter.convert(dateString), equalTo(expected));
} catch (NumberFormatException e) {
collector.addError(e);
}
}
} finally {
TimeZone.setDefault(original);
}
}
@Test
public void testDateTimeConverter_configuredPatterns_dateOnly_mismatch() throws IOException {
when(mockIndexingService.getSchema()).thenReturn(new Schema());
Properties config = new Properties();
config.put(StructuredData.DATETIME_PATTERNS, "M/d/yy ;dd MMM uuuu");
setupConfig.initConfig(config);
StructuredData.initFromConfiguration(mockIndexingService);
TimeZone original = TimeZone.getDefault();
TimeZone.setDefault(TimeZone.getTimeZone("GMT-04:00"));
try {
String rfc3339String = "2018-08-08T00:00:00.000-04:00";
DateTime expected = new DateTime(rfc3339String);
// Baseline so we don't chase unexpected errors below.
assertEquals("Baseline failure", rfc3339String, expected.toString());
Converter<Object, DateTime> converter = StructuredData.DATETIME_CONVERTER;
for (String dateString : new String[] {
// Time zones are still parsed from strings with no time.
"2018-08-08-07:00",
}) {
try {
collector.checkThat(dateString, converter.convert(dateString), not(equalTo(expected)));
} catch (NumberFormatException e) {
collector.addError(e);
}
}
} finally {
TimeZone.setDefault(original);
}
}
@Test
public void dateTimeConverter_fromDate() throws IOException {
setupConfig.initConfig(new Properties());
when(mockIndexingService.getSchema()).thenReturn(new Schema());
StructuredData.initFromConfiguration(mockIndexingService);
String rfc3339String = "2018-08-08T15:48:17.000-04:00";
// DATETIME_CONVERTER assumes the current time zone, so we need to
// construct an expected value in the local time zone.
DateTime expected = new DateTime(new DateTime(rfc3339String).getValue());
Converter<Object, DateTime> converter = StructuredData.DATETIME_CONVERTER;
java.util.Date input = java.util.Date.from(ZonedDateTime.parse(rfc3339String).toInstant());
assertThat(converter.convert(input), equalTo(expected));
}
@Test
public void dateConverter_fromString() throws IOException {
setupConfig.initConfig(new Properties());
when(mockIndexingService.getSchema()).thenReturn(new Schema());
StructuredData.initFromConfiguration(mockIndexingService);
Date expected = new Date().setYear(2018).setMonth(8).setDay(8);
Converter<Object, Date> converter = StructuredData.DATE_CONVERTER;
for (String dateString : new String[] {
// API Date class doesn't have a time zone, so anything will match.
// TODO(jlacey): We could construct offsets relative to the actual local time zone,
// rather than assuming that +14:00 and -11:00 will always test rollover.
"2018-08-08T15:48:17.000-07:00",
"2018-08-08 15:48:17-04:00",
"Wed, 8 Aug 2018 15:48:17 -0700",
"08 Aug 2018 15:48:17 +0100",
"2018-08-08T23:48:17-11:00", // 2018-08-09 in most local time zones.
"2018-08-08+14:00", // 2018-08-07 in most local time zones.
"2018-08-08",
}) {
try {
collector.checkThat(dateString, converter.convert(dateString), equalTo(expected));
} catch (NumberFormatException e) {
collector.addError(e);
}
}
}
@Test
public void dateConverter_fromString_noDate() throws IOException {
setupConfig.initConfig(new Properties());
when(mockIndexingService.getSchema()).thenReturn(new Schema());
StructuredData.initFromConfiguration(mockIndexingService);
Converter<Object, Date> converter = StructuredData.DATE_CONVERTER;
thrown.expect(NumberFormatException.class);
converter.convert("15:48:17-04:00");
}
@Test
public void dateConverter_fromString_unparsedCharacters() throws IOException {
setupConfig.initConfig(new Properties());
when(mockIndexingService.getSchema()).thenReturn(new Schema());
StructuredData.initFromConfiguration(mockIndexingService);
Converter<Object, Date> converter = StructuredData.DATE_CONVERTER;
thrown.expect(NumberFormatException.class);
converter.convert("2018-08-08T15:48:17.000-07:00 and so on");
}
@SuppressWarnings("unchecked")
@Override
protected F doBackward(T b) {
if(function instanceof Converter)
{
Converter<F, T> converter = (Converter<F, T>)function;
return converter.reverse().convert(b);
}
else
{
return super.doBackward(b);
}
}
/**
* Constructor for EnumAdapter.
* @param _enumClass Class<E>
* @param c Converter<String,E>
*/
public EnumAdapter(
Class<E> _enumClass,
Converter<String,E> c) {
super();
this.des = toUpper.andThen(c);
this.ser = c.reverse().andThen(toLower);
}
static NormalizedNodeContextSupport create(final JaxenDocument document,
final Converter<String, QNameModule> prefixes) {
final ConverterNamespaceContext context = new ConverterNamespaceContext(prefixes);
final NormalizedNodeNavigator navigator = new NormalizedNodeNavigator(context, document);
return new NormalizedNodeContextSupport(context, navigator);
}
@Override
public XPathExpression compileExpression(final SchemaPath schemaPath,
final Converter<String, QNameModule> prefixes, final String xpath) throws XPathExpressionException {
try {
return JaxenXPath.create(prefixes, schemaPath, xpath);
} catch (JaxenException e) {
throw new XPathExpressionException(e);
}
}
@Test
public void convert_toRequestObject() {
Converter<RlsProtoData.RouteLookupRequest, RouteLookupRequest> converter =
new RouteLookupRequestConverter().reverse();
RlsProtoData.RouteLookupRequest requestObject =
new RlsProtoData.RouteLookupRequest(
"server", "path", "target", ImmutableMap.of("key1", "val1"));
RouteLookupRequest proto = converter.convert(requestObject);
assertThat(proto.getServer()).isEqualTo("server");
assertThat(proto.getPath()).isEqualTo("path");
assertThat(proto.getTargetType()).isEqualTo("target");
assertThat(proto.getKeyMapMap()).containsExactly("key1", "val1");
}