Skip to content
This repository has been archived by the owner on Apr 18, 2023. It is now read-only.

Issue #5 - Added support for Map type; Updated to latest protobuf ver… #10

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@
/example/.idea
/example/.gradle
/example/build
/out
8 changes: 4 additions & 4 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -22,18 +22,18 @@ repositories {

[ compileJava, compileTestJava ]*.options*.encoding = 'UTF-8'

sourceCompatibility='1.7'
targetCompatibility='1.7'
sourceCompatibility='1.8'
targetCompatibility='1.8'

protobuf {
protoc {
artifact = 'com.google.protobuf:protoc:3.0.0-beta-1'
artifact = 'com.google.protobuf:protoc:3.5.1'
}
generatedFilesBaseDir = "$projectDir/src"
}

dependencies {
compile 'com.google.protobuf:protobuf-java:3.0.0-beta-1'
compile 'com.google.protobuf:protobuf-java:3.5.1'
testCompile 'junit:junit:4.12'
}

Expand Down
49 changes: 49 additions & 0 deletions src/main/java/net/badata/protobuf/converter/Converter.java
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ public static Converter create(final FieldsIgnore fieldsIgnore) {
* Create configured converter.
*
* @param configuration Parameters for conversion.
* @return New converter
*/
public static Converter create(final Configuration configuration) {
return new Converter(configuration);
Expand Down Expand Up @@ -202,6 +203,11 @@ private void fillDomainField(final FieldResolver fieldResolver, final MappingRes
if (FieldUtils.isComplexType(collectionType)) {
mappedValue = createDomainValueList(collectionType, mappedValue);
}
fieldWriter.write(fieldResolver, mappedValue);
break;
case MAP_MAPPING:
Class<?>[] mapTypes = FieldUtils.extractMapTypes(fieldResolver.getField());
mappedValue = createDomainValueMap(mapTypes[0], mapTypes[1], (Map)mappedValue);
case MAPPED:
default:
fieldWriter.write(fieldResolver, mappedValue);
Expand Down Expand Up @@ -245,6 +251,7 @@ private <T, E extends Message, K extends Collection> K toProtobuf(final Class<K>
return (K) protobufCollection;
}


/**
* Create Protobuf dto from domain object.
*
Expand Down Expand Up @@ -315,6 +322,11 @@ private void fillProtobufField(final FieldResolver fieldResolver, final MappingR
mappedValue = createProtobufValueList(protobufCollectionClass, fieldResolver.getDomainType(),
(Collection) mappedValue);
}
fieldWriter.write(fieldResolver, mappedValue);
break;
case MAP_MAPPING:
Class<?>[] mapTypes = MessageUtils.getMessageMapTypes(mappingResult.getDestination(), FieldUtils.createProtobufGetterName(fieldResolver));
mappedValue = createProtobufValueMap(mapTypes[0], mapTypes[1], (Map) mappedValue);
case MAPPED:
default:
fieldWriter.write(fieldResolver, mappedValue);
Expand All @@ -327,4 +339,41 @@ private <E extends Message> Collection<?> createProtobufValueList(final Class<E>
.toProtobuf((Class<? extends Collection>) domainCollectionClass, type, domainCollection);
}

private Map createProtobufValueMap(final Class keyClass, final Class valueClass, final Map mappedValue) {
boolean protoKey = false, protoValue = false;
if (FieldUtils.isComplexType(keyClass)) {
protoKey = true;
}
if (FieldUtils.isComplexType(valueClass)) {
protoValue = true;
}
Map protobufMap = new HashMap<>();
if (mappedValue != null) {
for (Iterator<Map.Entry> it = mappedValue.entrySet().iterator(); it.hasNext();) {
Map.Entry<?, ?> entry = it.next();
protobufMap.put(protoKey ? toProtobuf((Class<Message>)keyClass, entry.getKey()) : entry.getKey(),
protoValue ? toProtobuf((Class<Message>)valueClass, entry.getValue()) : entry.getValue());
}
}
return protobufMap;
}

private Map createDomainValueMap(final Class keyClass, final Class valueClass, Map mappedValue) {
boolean protoKey = false, protoValue = false;
if (FieldUtils.isComplexType(keyClass)) {
protoKey = true;
}
if (FieldUtils.isComplexType(valueClass)) {
protoValue = true;
}
Map domainMap = new HashMap<>();
if (mappedValue != null) {
for (Iterator<Map.Entry> it = mappedValue.entrySet().iterator(); it.hasNext();) {
Map.Entry<?, ?> entry = it.next();
domainMap.put(protoKey ? toDomain(keyClass, (Message)entry.getKey()) : entry.getKey(),
protoValue ? toDomain(valueClass, (Message)entry.getValue()) : entry.getValue());
}
}
return domainMap;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public FieldsIgnore add(final Class<?> ignoredClass, final String... fields) {
* Add all fields from another {@link net.badata.protobuf.converter.FieldsIgnore FieldsIgnore} instance.
*
* @param ignoredFields Instance of {@link net.badata.protobuf.converter.FieldsIgnore FieldsIgnore}.
* @return
* @return Returns FieldsIgnore
*/
public FieldsIgnore addAll(final FieldsIgnore ignoredFields) {
ignoreMapping.putAll(ignoredFields.ignoreMapping);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ public <T extends Message> MappingResult mapToDomainField(final FieldResolver fi
if (FieldUtils.isCollectionType(fieldResolver.getField())) {
return new MappingResult(MappingResult.Result.COLLECTION_MAPPING, protobufFieldValue, domain);
}
if (FieldUtils.isMapType(fieldResolver.getField())) {
return new MappingResult(MappingResult.Result.MAP_MAPPING, protobufFieldValue, domain);
}
return new MappingResult(MappingResult.Result.MAPPED, protobufFieldValue, domain);
}

Expand Down Expand Up @@ -105,6 +108,9 @@ public <T extends Message.Builder> MappingResult mapToProtobufField(final FieldR
if (FieldUtils.isCollectionType(fieldResolver.getField())) {
return new MappingResult(MappingResult.Result.COLLECTION_MAPPING, domainFieldValue, protobufBuilder);
}
if (FieldUtils.isMapType(fieldResolver.getField())) {
return new MappingResult(MappingResult.Result.MAP_MAPPING, domainFieldValue, protobufBuilder);
}
return new MappingResult(MappingResult.Result.MAPPED, domainFieldValue, protobufBuilder);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,11 @@ public enum Result {
/**
* Collection field is mapped.
*/
COLLECTION_MAPPING;
COLLECTION_MAPPING,
/**
* Collection field is mapped.
*/
MAP_MAPPING
}
}

43 changes: 43 additions & 0 deletions src/main/java/net/badata/protobuf/converter/utils/FieldUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

package net.badata.protobuf.converter.utils;

import java.util.Map;
import net.badata.protobuf.converter.annotation.ProtoClass;
import net.badata.protobuf.converter.annotation.ProtoClasses;
import net.badata.protobuf.converter.resolver.FieldResolver;
Expand All @@ -38,6 +39,8 @@ public final class FieldUtils {
private static final String BOOLEAN_GETTER_PREFIX = "is";
private static final String PROTOBUF_LIST_GETTER_POSTFIX = "List";
private static final String PROTOBUF_LIST_SETTER_PREFIX = "addAll";
private static final String PROTOBUF_MAP_GETTER_POSTFIX = "Map";
private static final String PROTOBUF_MAP_SETTER_PREFIX = "putAll";

/**
* Check whether field has own mapper.
Expand Down Expand Up @@ -81,6 +84,26 @@ public static boolean isCollectionType(final Class<?> type) {
return Collection.class.isAssignableFrom(type);
}

/**
* Check whether field type implements Map interface.
*
* @param field Testing field.
* @return true if field type implements {@link java.util.Map}, otherwise false.
*/
public static boolean isMapType(final Field field) {
return isMapType(field.getType());
}

/**
* Check whether class implements Map interface.
*
* @param type Testing class.
* @return true if class implements {@link java.util.Map}, otherwise false.
*/
private static boolean isMapType(final Class<?> type) {
return Map.class.isAssignableFrom(type);
}

/**
* Create protobuf getter name for domain field.
*
Expand All @@ -105,6 +128,9 @@ public static String createProtobufGetterName(final FieldResolver fieldResolver)
if (isCollectionType(fieldResolver.getProtobufType())) {
return getterName + PROTOBUF_LIST_GETTER_POSTFIX;
}
if (isMapType(fieldResolver.getProtobufType())) {
return getterName + PROTOBUF_MAP_GETTER_POSTFIX;
}
return getterName;
}

Expand All @@ -118,6 +144,9 @@ public static String createProtobufSetterName(final FieldResolver fieldResolver)
if (isCollectionType(fieldResolver.getProtobufType())) {
return StringUtils.createMethodName(PROTOBUF_LIST_SETTER_PREFIX, fieldResolver.getProtobufName());
}
if (isMapType(fieldResolver.getProtobufType())) {
return StringUtils.createMethodName(PROTOBUF_MAP_SETTER_PREFIX, fieldResolver.getProtobufName());
}
return StringUtils.createMethodName(SETTER_PREFIX, fieldResolver.getProtobufName());
}

Expand Down Expand Up @@ -155,6 +184,20 @@ public static Class<?> extractCollectionType(final Field field) {
return (Class<?>) genericType.getActualTypeArguments()[0];
}

/**
* Extract parameter types of the map.
*
* @param field Field with type derived from {@link java.util.Map}.
* @return Map generic types.
*/
public static Class<?>[] extractMapTypes(Field field) {
ParameterizedType genericType = (ParameterizedType) field.getGenericType();
Class<?>[] result = new Class[2];
result[0] = (Class<?>) genericType.getActualTypeArguments()[0];
result[1] = (Class<?>) genericType.getActualTypeArguments()[1];
return result;
}

/**
* Extract protobuf field type from type converter.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,21 @@ public static Class<? extends Message> getMessageCollectionType(final Object obj
}
}

/**
* Extract Protobuf message types from map.
*
* @param object Object that contains collection of Protobuf messages.
* @param methodName getter method name.
* @return Class of the Protobuf message.
*/
@SuppressWarnings("unchecked")
public static Class<?>[] getMessageMapTypes(final Object object, final String methodName) {
try {
ParameterizedType stringMapType = (ParameterizedType) object.getClass().getMethod(methodName)
.getGenericReturnType();
return new Class<?>[]{(Class<?>) stringMapType.getActualTypeArguments()[0], (Class<?>) stringMapType.getActualTypeArguments()[1]};
} catch (NoSuchMethodException e) {
return new Class<?>[]{String.class, Message.class};
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
package net.badata.protobuf.converter.writer;

import com.google.protobuf.Message;
import java.util.Map;
import net.badata.protobuf.converter.exception.WriteException;
import net.badata.protobuf.converter.resolver.FieldResolver;
import net.badata.protobuf.converter.type.TypeConverter;
Expand Down Expand Up @@ -91,6 +92,9 @@ private Class<?> extractValueClass(final Object value) {
if (Collection.class.isAssignableFrom(valueClass)) {
return Iterable.class;
}
if (Map.class.isAssignableFrom(valueClass)) {
return Map.class;
}
return valueClass;
}
}
12 changes: 12 additions & 0 deletions src/test/java/net/badata/protobuf/converter/ConverterTest.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package net.badata.protobuf.converter;

import com.google.protobuf.ByteString;
import java.util.Collections;
import net.badata.protobuf.converter.domain.ConverterDomain;
import net.badata.protobuf.converter.proto.ConverterProto;
import org.junit.Assert;
Expand Down Expand Up @@ -58,6 +59,8 @@ private void createTestProtobuf() {
.addComplexSetValue(ConverterProto.PrimitiveTest.newBuilder().setIntValue(1002))
.setBytesValue(ByteString.copyFrom(new byte[]{ 0, 1, 3, 7 }))
.setRecursiveValue(ConverterProto.ConverterTest.newBuilder().setIntValue(1))
.putSimpleMapValue("key", "value")
.putComplexMapValue("key", ConverterProto.PrimitiveTest.newBuilder().setIntValue(1001).build())
.build();
}

Expand Down Expand Up @@ -100,6 +103,9 @@ private void createTestDomain() {
ConverterDomain.Test nestedValue = new ConverterDomain.Test();
nestedValue.setIntValue(1);
testDomain.setRecursiveValue(nestedValue);

testDomain.setSimpleMapValue(Collections.singletonMap("key", "value"));
testDomain.setComplexMapValue(Collections.singletonMap("key", primitiveTestItem));
}

private void createIgnoredFieldsMap() {
Expand Down Expand Up @@ -158,6 +164,10 @@ public void testProtobufToDomain() {

Assert.assertEquals(testProtobuf.getBytesValue(), result.getBytesValue());
Assert.assertEquals((Object) testProtobuf.getRecursiveValue().getIntValue(), result.getRecursiveValue().getIntValue());

Assert.assertEquals(testProtobuf.getSimpleMapValueMap(), result.getSimpleMapValue());
Assert.assertEquals(testProtobuf.getComplexMapValueMap().get("key").getIntValue(),
result.getComplexMapValue().get("key").getIntValue());
}

@Test
Expand Down Expand Up @@ -215,6 +225,8 @@ public void testDomainToProtobuf() {

Assert.assertTrue(result.getComplexNullableCollectionValueList().isEmpty());
Assert.assertEquals((Object) testDomain.getRecursiveValue().getIntValue(), result.getRecursiveValue().getIntValue());
Assert.assertEquals(testDomain.getSimpleMapValue(), result.getSimpleMapValueMap());
Assert.assertEquals(testDomain.getComplexMapValue(), result.getComplexMapValueMap());
}

@Test
Expand Down
17 changes: 17 additions & 0 deletions src/test/java/net/badata/protobuf/converter/DefaultMapperTest.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package net.badata.protobuf.converter;

import java.util.Collections;
import net.badata.protobuf.converter.domain.MappingDomain;
import net.badata.protobuf.converter.exception.MappingException;
import net.badata.protobuf.converter.mapping.DefaultMapperImpl;
Expand Down Expand Up @@ -64,6 +65,8 @@ private void createTestProtobuf() {
.setNestedValue(MappingProto.NestedTest.newBuilder().setStringValue("4"))
.addStringListValue("10")
.addNestedListValue(MappingProto.NestedTest.newBuilder().setStringValue("20"))
.putAllSimpleMap(Collections.singletonMap("key", "value"))
.putAllNestedMap(Collections.singletonMap("key", MappingProto.NestedTest.newBuilder().setStringValue("20").build()))
.build();
}

Expand All @@ -82,6 +85,8 @@ private void createTestDomain() {
MappingDomain.NestedTest nestedList = new MappingDomain.NestedTest();
nested.setStringValue("120");
testDomain.setNestedListValue(Arrays.asList(nestedList));
testDomain.setSimpleMap(Collections.singletonMap("key", "value"));
testDomain.setNestedMap(Collections.singletonMap("key", nested));
}

private void createPrimitiveTestDomain() {
Expand Down Expand Up @@ -191,6 +196,18 @@ public void testMapCollectionToProtobuf() throws MappingException {
testMappingResult(result, Result.COLLECTION_MAPPING, testDomain.getNestedListValue(), protobufBuilder);
}

@Test
public void testMapMappingToProtobuf() throws MappingException {
exception = ExpectedException.none();
MappingProto.MappingTest.Builder protobufBuilder = MappingProto.MappingTest.newBuilder();
MappingResult result = mapper
.mapToProtobufField(findDomainField("simpleMap"), testDomain, protobufBuilder);
testMappingResult(result, Result.MAP_MAPPING, testDomain.getSimpleMap(), protobufBuilder);

result = mapper.mapToProtobufField(findDomainField("nestedMap"), testDomain, protobufBuilder);
testMappingResult(result, Result.MAP_MAPPING, testDomain.getNestedMap(), protobufBuilder);
}

@Test
public void testMapNestedToProtobuf() throws MappingException {
exception = ExpectedException.none();
Expand Down
Loading