ProtoTypeAdapterFactory.java

/*
 * Copyright 2022 Providence Authors
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package net.morimekta.proto.gson;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.protobuf.ByteString;
import com.google.protobuf.Descriptors;
import com.google.protobuf.Message;
import net.morimekta.proto.ProtoEnum;
import net.morimekta.proto.ProtoMessage;
import net.morimekta.proto.gson.adapter.ByteStringMapKeyTypeAdapter;
import net.morimekta.proto.gson.adapter.ByteStringTypeAdapter;
import net.morimekta.proto.gson.adapter.ProtoEnumMapKeyTypeAdapter;
import net.morimekta.proto.gson.adapter.ProtoEnumTypeAdapter;
import net.morimekta.proto.gson.adapter.ProtoMessageTypeAdapter;

import java.lang.reflect.ParameterizedType;
import java.util.Map;

import static net.morimekta.proto.ProtoEnum.getEnumDescriptorUnchecked;
import static net.morimekta.proto.ProtoEnum.isProtoEnumClass;

/**
 * Factory for creating gson adaptors for proto types.
 */
public class ProtoTypeAdapterFactory
        implements TypeAdapterFactory {
    private final ProtoTypeOptions options;

    /**
     * Instantiate type adapter factory.
     */
    public ProtoTypeAdapterFactory() {
        this(new ProtoTypeOptions());
    }

    /**
     * Instantiate type adapter factory.
     *
     * @param options Options on adapters.
     */
    public ProtoTypeAdapterFactory(ProtoTypeOptions options) {
        this.options = options;
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
        try {
            if (ByteString.class.isAssignableFrom(type.getRawType())) {
                // ByteString
                return (TypeAdapter<T>) new ByteStringTypeAdapter();
            } else if (Message.class.isAssignableFrom(type.getRawType())) {
                // Message
                Descriptors.Descriptor descriptor = ProtoMessage.getMessageDescriptor(type.getRawType());
                return (TypeAdapter<T>) new ProtoMessageTypeAdapter(descriptor, options);
            } else if (isProtoEnumClass(type.getRawType())) {
                // Enum
                ProtoEnum<?> descriptor = getEnumDescriptorUnchecked(type.getRawType());
                return (TypeAdapter<T>) new ProtoEnumTypeAdapter<>(descriptor, options);
            } else if (Map.class.isAssignableFrom(type.getRawType())) {
                if (type.getType() instanceof ParameterizedType) {
                    ParameterizedType pt = (ParameterizedType) type.getType();
                    if (pt.getActualTypeArguments().length == 2) {
                        if (pt.getActualTypeArguments()[0] instanceof Class) {
                            Class<?> keyType = (Class<?>) pt.getActualTypeArguments()[0];
                            if (isProtoEnumClass(keyType)) {
                                // Map<Enum, *>
                                ProtoEnum<?> descriptor = getEnumDescriptorUnchecked(keyType);
                                TypeAdapter<?> valueAdapter = gson.getAdapter((Class<?>) pt.getActualTypeArguments()[1]);
                                return (TypeAdapter<T>) new ProtoEnumMapKeyTypeAdapter<>(
                                        descriptor,
                                        options,
                                        valueAdapter,
                                        (Class<? extends Map<?, ?>>) type.getRawType());
                            } else if (ByteString.class.isAssignableFrom(keyType)) {
                                // Map<ByteString, *>
                                TypeAdapter<?> valueAdapter = gson.getAdapter((Class<?>) pt.getActualTypeArguments()[1]);
                                return (TypeAdapter<T>) new ByteStringMapKeyTypeAdapter<>(
                                        options,
                                        valueAdapter,
                                        (Class<? extends Map<?, ?>>) type.getRawType());
                            }
                        }
                    }
                }
            }
        } catch (IllegalArgumentException ignore) {
            // ignore
        }
        return null;
    }
}