Home > Back-end >  How would I make a ProtobufEnum attribute converter?
How would I make a ProtobufEnum attribute converter?

Time:09-17

I am trying to find a common way to store the that are generated by protobuf to an Attribute Converter.

Here's what I started with

package com.devhaus.als.portfolio.domain;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.protobuf.ProtocolMessageEnum;
import lombok.Getter;
import org.jetbrains.annotations.Contract;
import org.springframework.stereotype.Component;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

@Component
@Converter(autoApply = true)
public class ProtobufEnumConverter implements AttributeConverter<ProtocolMessageEnum, String> {

    @Override
    public String convertToDatabaseColumn(final ProtocolMessageEnum attribute) {

        // I would've prefered string, but it may be more difficult.
        return attribute.getDescriptorForType().getName()   "/"   attribute.getNumber();
    }

    @Override
    public ProtocolMessageEnum convertToEntityAttribute(final String dbData) {

        // HOW!?!
        return null;
    }
}

CodePudding user response:

I assume the implementation is an enum :

@Component
@Converter(autoApply = true)
public class ProtobufEnumConverter implements AttributeConverter<ProtocolMessageEnum, String> {

    private final static String SEP = "/";

    @Override
    public String convertToDatabaseColumn(final ProtocolMessageEnum attribute) {
        if(attribute == null) return null;
        if(attribute instanceof Enum) {
            Enum<?> e = (Enum<?>) attribute;
            return e.getClass().getName()   SEP   e.name();
        } else {
            throw IllegalArgumentException("not an enum");
        }
    }

    @Override
    public ProtocolMessageEnum convertToEntityAttribute(final String dbData) {
        if(dbData == null) return null;
        String[] tab = dbData.split(SEP);
        try {
            Class<? extends Enum> clazz = (Class<? extends Enum>) Class.forName(tab[0]);
            Enum res = Enum.valueOf(clazz, tab[1]);
            return (ProtocolMessageEnum) res;
        } catch(ClassNotFoundException e) {
            throw new IllegalArgumentException(e);
        }
    }
}
  • Related