2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.directives;
10 import java.io.IOException;
11 import java.io.Writer;
12 import java.util.List;
15 import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.FtlTemplate;
16 import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Annotation;
17 import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Annotation.Parameter;
19 import com.google.common.collect.Lists;
21 import freemarker.core.Environment;
22 import freemarker.template.SimpleSequence;
23 import freemarker.template.TemplateDirectiveBody;
24 import freemarker.template.TemplateDirectiveModel;
25 import freemarker.template.TemplateException;
26 import freemarker.template.TemplateModel;
29 * Add annotations to freemarker template.
31 public class AnnotationsDirective implements TemplateDirectiveModel {
33 private static final String OBJECT = "object";
36 public void execute(Environment env, Map params, TemplateModel[] loopVars,
37 TemplateDirectiveBody body) throws TemplateException, IOException {
38 Object object = params.get(OBJECT);
39 List<Annotation> annotations = Lists.newArrayList();
42 if (object instanceof SimpleSequence)
43 annotations = ((SimpleSequence) object).toList();
44 else if (object instanceof FtlTemplate) {
45 annotations = ((FtlTemplate) object).getAnnotations();
47 throw new IllegalArgumentException(
48 "Object must be a SimpleSequence or instance of "
49 + FtlTemplate.class + "but was "
53 Writer out = env.getOut();
54 StringBuilder build = new StringBuilder();
55 writeAnnotations(annotations, build, "");
57 if (!annotations.isEmpty())
58 out.write(build.toString().toCharArray());
61 static void writeAnnotations(List<Annotation> annotations,
62 StringBuilder build, String linePrefix) {
63 for (Annotation annotation : annotations) {
64 build.append(linePrefix + "@");
65 build.append(annotation.getName());
66 if (!annotation.getParams().isEmpty()) {
68 for (Parameter param : annotation.getParams()) {
69 build.append(param.getKey());
71 build.append(fixString(param.getValue()));
74 build.setCharAt(build.length() - 2, ')');
76 build.append(System.lineSeparator());
80 private static String fixString(String value) {
81 // TODO replace with compress single line if possible
82 return value.replaceAll("\\r\\n|\\r|\\n", " ").replaceAll(" +", " ");