Java Code Examples for com.google.common.base.Converter#convert()

The following examples show how to use com.google.common.base.Converter#convert() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: IndexingItemBuilder.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
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));
}
 
Example 2
Source File: BindContentProviderBuilder.java    From kripton with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
	}
}
 
Example 3
Source File: BindTypeContext.java    From kripton with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 4
Source File: RlsProtoConvertersTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example 5
Source File: StructuredDataTest.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
@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");
}
 
Example 6
Source File: StructuredDataTest.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
@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");
}
 
Example 7
Source File: StructuredDataTest.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
@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");
}
 
Example 8
Source File: RlsProtoConvertersTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@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");
}
 
Example 9
Source File: RlsProtoConvertersTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void convert_toResponseProto() {
  Converter<RouteLookupResponse, RlsProtoData.RouteLookupResponse> converter =
      new RouteLookupResponseConverter();
  RouteLookupResponse proto = RouteLookupResponse.newBuilder()
      .addTargets("target")
      .setHeaderData("some header data")
      .build();

  RlsProtoData.RouteLookupResponse object = converter.convert(proto);

  assertThat(object.getTargets()).containsExactly("target");
  assertThat(object.getHeaderData()).isEqualTo("some header data");
}
 
Example 10
Source File: RlsProtoConvertersTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void convert_toResponseObject() {
  Converter<RlsProtoData.RouteLookupResponse, RouteLookupResponse> converter =
      new RouteLookupResponseConverter().reverse();

  RlsProtoData.RouteLookupResponse object =
      new RlsProtoData.RouteLookupResponse(ImmutableList.of("target"), "some header data");

  RouteLookupResponse proto = converter.convert(object);

  assertThat(proto.getTargetsList()).containsExactly("target");
  assertThat(proto.getHeaderData()).isEqualTo("some header data");
}
 
Example 11
Source File: BindDataSourceSubProcessor.java    From kripton with Apache License 2.0 4 votes vote down vote up
/**
 * Create DAO definition.
 *
 * @param schema
 *            the schema
 * @param globalBeanElements
 *            the global bean elements
 * @param globalDaoElements
 *            the global dao elements
 * @param daoItem
 *            the dao item
 */
protected void createSQLDaoDefinition(SQLiteDatabaseSchema schema,
		final Map<String, TypeElement> globalBeanElements, final Map<String, TypeElement> globalDaoElements,
		String daoItem) {
	Element daoElement = globalDaoElements.get(daoItem);

	if (daoElement.getKind() != ElementKind.INTERFACE) {
		String msg = String.format("Class %s: only interfaces can be annotated with @%s annotation",
				daoElement.getSimpleName().toString(), BindDao.class.getSimpleName());
		throw (new InvalidKindForAnnotationException(msg));
	}

	M2MEntity entity = M2MEntity.extractEntityManagedByDAO((TypeElement) daoElement);

	// add to current schema generated entities too
	for (GeneratedTypeElement genItem : this.generatedEntities) {
		if (genItem.getQualifiedName().equals(entity.getQualifiedName())) {
			schema.generatedEntities.add(genItem);
		}
	}

	boolean generated = daoElement.getAnnotation(BindGeneratedDao.class) != null;

	final SQLiteDaoDefinition currentDaoDefinition = new SQLiteDaoDefinition(schema, daoItem,
			(TypeElement) daoElement, entity.getClassName().toString(), generated);

	// content provider management
	BindContentProviderPath daoContentProviderPath = daoElement.getAnnotation(BindContentProviderPath.class);
	if (daoContentProviderPath != null) {
		currentDaoDefinition.contentProviderEnabled = true;
		currentDaoDefinition.contentProviderPath = daoContentProviderPath.path();
		currentDaoDefinition.contentProviderTypeName = daoContentProviderPath.typeName();

		if (StringUtils.isEmpty(currentDaoDefinition.contentProviderTypeName)) {
			Converter<String, String> convert = CaseFormat.UPPER_CAMEL.converterTo(CaseFormat.LOWER_UNDERSCORE);
			AssertKripton.assertTrue(currentDaoDefinition.getParent().contentProvider != null,
					"DAO '%s' has an inconsistent content provider definition, perhaps you forget to use @%s in data source interface?",
					currentDaoDefinition.getElement().getQualifiedName(),
					BindContentProvider.class.getSimpleName());
			currentDaoDefinition.contentProviderTypeName = currentDaoDefinition
					.getParent().contentProvider.authority + "."
					+ convert.convert(currentDaoDefinition.getSimpleEntityClassName());
		}
	}

	// dao is associated to an entity is not contained in analyzed class
	// set.
	if (!globalBeanElements.containsKey(currentDaoDefinition.getEntityClassName())
			&& !isGeneratedEntity(currentDaoDefinition.getEntityClassName())) {
		throw (new InvalidBeanTypeException(currentDaoDefinition));
	}

	schema.add(currentDaoDefinition);

	fillMethods(currentDaoDefinition, daoElement);

	// get @annotation associated to many 2 many relationship
	BindDaoMany2Many daoMany2Many = daoElement.getAnnotation(BindDaoMany2Many.class);

	// dao definition must have >0 method associated to query
	if (currentDaoDefinition.getCollection().size() == 0 && daoMany2Many == null) {
		throw (new DaoDefinitionWithoutAnnotatedMethodException(currentDaoDefinition));
	}
}
 
Example 12
Source File: AbstractEntityHandler.java    From Orienteer with Apache License 2.0 4 votes vote down vote up
protected Object convertValueFromEntity(String entityFieldName, Object value) {
	Converter<Object, Object> converter = mappingConvertors.get(entityFieldName);
	return converter==null?value:converter.convert(value);
}