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

com.atlassian.bamboo.specs.codegen.emitters.fragment.VarargArgumentSetterEmitter Maven / Gradle / Ivy

There is a newer version: 10.1.0
Show newest version
package com.atlassian.bamboo.specs.codegen.emitters.fragment;

import com.atlassian.bamboo.specs.api.codegen.CodeEmitter;
import com.atlassian.bamboo.specs.api.codegen.CodeGenerationContext;
import com.atlassian.bamboo.specs.api.codegen.CodeGenerationException;
import com.atlassian.bamboo.specs.codegen.emitters.CodeGenerationUtils;
import com.atlassian.bamboo.specs.codegen.emitters.value.ValueEmitterFactory;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;

/**
 * Default code generator for any {@link Iterable} field of {@link com.atlassian.bamboo.specs.api.model.EntityProperties} instance.
 */
public class VarargArgumentSetterEmitter implements CodeEmitter> {
    final String methodName;

    public VarargArgumentSetterEmitter(final String methodName) {
        this.methodName = methodName;
    }


    /**
     * Generates invocation of a setter method with a variable length argument list.
     */
    @NotNull
    @Override
    public String emitCode(@NotNull final CodeGenerationContext context, @NotNull final Iterable iterable) throws CodeGenerationException {
        StringBuilder builder = new StringBuilder(".").append(methodName).append("(");
        context.incIndentation();

        List valuesAndFails = new ArrayList<>();
        Set failed = new HashSet<>();
        boolean hasNonEmptyValue = false;
        int count = 0;
        for (Object item : iterable) {
            try {
                CodeEmitter codeEmitter = ValueEmitterFactory.emitterFor(item);
                String argumentCode = codeEmitter.emitCode(context, item);
                valuesAndFails.add(argumentCode);
                if (StringUtils.isNotEmpty(argumentCode)) {
                    hasNonEmptyValue = true;
                }
            } catch (CodeGenerationException e) {
                valuesAndFails.add(e.getMessage());
                failed.add(count);
            }
            count++;
        }
        if (!failed.isEmpty() || hasNonEmptyValue) {
            CodeGenerationUtils.appendCommaSeparatedList(context,
                    builder,
                    valuesAndFails,
                    failed);
            context.decIndentation();
            return builder.append(")").toString();
        }
        context.decIndentation();
        return "";
    }
}