All Downloads are FREE. Search and download functionalities are using the official Maven repository.

pocketknife.internal.codegen.builder.BundleMethodBinding Maven / Gradle / Ivy

There is a newer version: 3.2.1
Show newest version
package pocketknife.internal.codegen.builder;

import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.MethodSpec;
import org.apache.commons.lang3.StringUtils;
import pocketknife.internal.codegen.BundleFieldBinding;
import pocketknife.internal.codegen.KeySpec;
import pocketknife.internal.codegen.MethodBinding;
import pocketknife.internal.codegen.TypeUtil;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import static javax.lang.model.element.Modifier.PUBLIC;

public class BundleMethodBinding extends MethodBinding {

    private static final String RETURN_VAR_NAME_ROOT = "bundle";

    private final String name;

    private final List fields = new ArrayList();

    public BundleMethodBinding(String name) {
        this.name = name;
    }

    public void addField(BundleFieldBinding fieldBinding) {
        if (fields.contains(fieldBinding)) {
            throw new IllegalStateException("Cannot have multiple arguments named: " + fieldBinding.getName());
        }
        fields.add(fieldBinding);
    }

    @Override
    public Set getKeys() {
        Set keys = new LinkedHashSet();
        for (BundleFieldBinding field : fields) {
            keys.add(field.getKey());
        }
        return keys;
    }

    @Override
    public MethodSpec generateMethodSpec(TypeUtil typeUtil) {
        String returnVarName = getReturnVarName(RETURN_VAR_NAME_ROOT);

        MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(name)
                .addAnnotation(Override.class)
                .addModifiers(PUBLIC)
                .returns(ClassName.get(typeUtil.bundleType))
                .addStatement("$T $N = new $T()", ClassName.get(typeUtil.bundleType), returnVarName, ClassName.get(typeUtil.bundleType));

        for (BundleFieldBinding fieldBinding : fields) {
            methodBuilder.addParameter(ClassName.get(fieldBinding.getType()), fieldBinding.getName());
            String keyValue;
            String stmt = "$N.put$L(";
            KeySpec key = fieldBinding.getKey();
            if (StringUtils.isBlank(key.getName())) {
                keyValue = key.getValue();
                stmt = stmt.concat("$S");
            } else {
                keyValue = key.getName();
                stmt = stmt.concat("$N");
            }
            stmt = stmt.concat(", $N)");
            methodBuilder.addStatement(stmt, returnVarName, fieldBinding.getBundleType(), keyValue, fieldBinding.getName());
        }

        methodBuilder.addStatement("return $N", returnVarName);

        return methodBuilder.build();
    }

    @Override
    public List getFields() {
        return fields;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy