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

com.atlassian.bamboo.specs.codegen.emitters.value.SetEmitter Maven / Gradle / Ivy

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

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.util.SetBuilder;
import org.jetbrains.annotations.NotNull;

import java.util.Collections;
import java.util.Set;

public class SetEmitter implements CodeEmitter> {
    @NotNull
    @Override
    public String emitCode(@NotNull final CodeGenerationContext context, @NotNull final Set set) throws CodeGenerationException {
        StringBuilder builder = new StringBuilder();

        if (set.isEmpty()) {
            return context.importClassName(Collections.class) + ".emptySet()"; //defensive code, such field should've been filtered
        }
        builder.append("new ").append(context.importClassName(SetBuilder.class)).append("()");
        context.incIndentation();
        for (Object entry : set) {
            StringBuilder itemBuilder = new StringBuilder();
            try {
                itemBuilder.append(context.newLine());
                itemBuilder.append(".put(");
                CodeEmitter codeEmitter = ValueEmitterFactory.emitterFor(entry);
                itemBuilder.append(codeEmitter.emitCode(context, entry));
                itemBuilder.append(")");
                builder.append(itemBuilder);
            } catch (CodeGenerationException e) {
                builder.append(context.newLine());
                builder.append("//Could not generate set item with value: ").append(entry);
            }
        }

        builder.append(context.newLine());
        builder.append(".build()");
        context.decIndentation();
        return builder.toString();
    }
}