1 /* 2 * Copyright (C) 2014 Google, Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package dagger.internal.codegen.writer; 17 18 import com.google.common.collect.FluentIterable; 19 import com.google.common.collect.Iterables; 20 import com.google.common.collect.Maps; 21 import com.google.common.collect.Sets; 22 import java.io.IOException; 23 import java.util.Map.Entry; 24 import java.util.Set; 25 import java.util.SortedMap; 26 27 import static dagger.internal.codegen.writer.Writables.toStringWritable; 28 29 public final class AnnotationWriter implements Writable, HasClassReferences { 30 private final ClassName annotationName; 31 private final Set<HasClassReferences> memberReferences = Sets.newLinkedHashSet(); 32 private final SortedMap<String, Writable> memberMap = Maps.newTreeMap(); 33 34 AnnotationWriter(ClassName annotationName) { 35 this.annotationName = annotationName; 36 } 37 38 public void setValue(String value) { 39 setMember("value", value); 40 } 41 42 public void setMember(String name, int value) { 43 memberMap.put(name, toStringWritable(value)); 44 } 45 46 public void setMember(String name, String value) { 47 memberMap.put(name, toStringWritable(StringLiteral.forValue(value))); 48 } 49 50 public <T extends Enum<T>> void setMember(String name, T value) { 51 Snippet snippet = Snippet.format("%s.%s", ClassName.fromClass(value.getClass()), value); 52 memberMap.put(name, snippet); 53 memberReferences.add(snippet); 54 } 55 56 @Override 57 public Appendable write(Appendable appendable, Context context) throws IOException { 58 appendable.append('@'); 59 annotationName.write(appendable, context); 60 if (!memberMap.isEmpty()) { 61 appendable.append('('); 62 if (memberMap.size() == 1) { 63 Entry<String, Writable> onlyEntry = Iterables.getOnlyElement(memberMap.entrySet()); 64 if (!onlyEntry.getKey().equals("value")) { 65 appendable.append(onlyEntry.getKey()).append(" = "); 66 } 67 onlyEntry.getValue().write(appendable, context); 68 } 69 appendable.append(')'); 70 } 71 return appendable; 72 } 73 74 @Override 75 public Set<ClassName> referencedClasses() { 76 return FluentIterable.from(memberReferences) 77 .append(annotationName) 78 .transformAndConcat(HasClassReferences.COMBINER) 79 .toSet(); 80 } 81 } 82