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

com.atlassian.bamboo.specs.codegen.emitters.value.MapEmitter 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.MapBuilder;
import org.jetbrains.annotations.NotNull;

import java.util.Collections;
import java.util.Map;

/**
 * Generates code creating a Map.
 */
public class MapEmitter implements CodeEmitter> {

    @NotNull
    @Override
    public String emitCode(@NotNull final CodeGenerationContext context, @NotNull final Map value) throws CodeGenerationException {
        StringBuilder builder = new StringBuilder();

        final Map map = value;
        if (map.isEmpty()) {
            return context.importClassName(Collections.class) + ".emptyMap()"; //garmar: defensive code, such field should've been filtered
        }
        builder.append("new ").append(context.importClassName(MapBuilder.class)).append("()");
        context.incIndentation();

        for (Map.Entry entry : map.entrySet()) {
            StringBuilder itemBuilder = new StringBuilder();
            try {
                itemBuilder.append(context.newLine());
                itemBuilder.append(".put(");
                CodeEmitter codeEmitter = ValueEmitterFactory.emitterFor(entry.getKey());
                itemBuilder.append(codeEmitter.emitCode(context, entry.getKey()));
                itemBuilder.append(", ");
                CodeEmitter codeEmitter2 = ValueEmitterFactory.emitterFor(entry.getValue());
                itemBuilder.append(codeEmitter2.emitCode(context, entry.getValue()));
                itemBuilder.append(")");
                builder.append(itemBuilder);
            } catch (CodeGenerationException e) {
                builder.append(context.newLine());
                builder.append("//Could not generate map item with key: ").append(entry.getKey());
            }
        }
        builder.append(context.newLine());
        builder.append(".build()");
        context.decIndentation();
        return builder.toString();
    }
}