View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  
20  package org.apache.myfaces.tobago.apt.processor;
21  
22  
23  import org.apache.commons.io.IOUtils;
24  import org.apache.commons.lang.StringUtils;
25  import org.apache.myfaces.tobago.apt.AnnotationUtils;
26  import org.apache.myfaces.tobago.apt.annotation.ExtensionTag;
27  import org.apache.myfaces.tobago.apt.annotation.SimpleTag;
28  import org.apache.myfaces.tobago.apt.annotation.Tag;
29  import org.apache.myfaces.tobago.apt.annotation.TagAttribute;
30  import org.apache.myfaces.tobago.apt.annotation.Taglib;
31  import org.apache.myfaces.tobago.apt.annotation.UIComponentTag;
32  import org.apache.myfaces.tobago.apt.annotation.UIComponentTagAttribute;
33  import org.apache.myfaces.tobago.apt.annotation.ValidatorTag;
34  import org.w3c.dom.Document;
35  import org.w3c.dom.Element;
36  
37  import javax.annotation.processing.SupportedAnnotationTypes;
38  import javax.annotation.processing.SupportedOptions;
39  import javax.lang.model.element.ExecutableElement;
40  import javax.lang.model.element.PackageElement;
41  import javax.lang.model.element.TypeElement;
42  import javax.tools.FileObject;
43  import javax.tools.StandardLocation;
44  import javax.xml.parsers.DocumentBuilder;
45  import javax.xml.parsers.DocumentBuilderFactory;
46  import javax.xml.parsers.ParserConfigurationException;
47  import javax.xml.transform.OutputKeys;
48  import javax.xml.transform.Transformer;
49  import javax.xml.transform.TransformerException;
50  import javax.xml.transform.TransformerFactory;
51  import javax.xml.transform.dom.DOMSource;
52  import javax.xml.transform.stream.StreamResult;
53  import java.io.IOException;
54  import java.io.Writer;
55  import java.util.ArrayList;
56  import java.util.Collections;
57  import java.util.Comparator;
58  import java.util.HashSet;
59  import java.util.List;
60  import java.util.Locale;
61  import java.util.Map;
62  import java.util.Set;
63  
64  @SupportedAnnotationTypes({
65      "org.apache.myfaces.tobago.apt.annotation.Tag",
66      "org.apache.myfaces.tobago.apt.annotation.TagAttribute",
67      "org.apache.myfaces.tobago.apt.annotation.Taglib"})
68  @SupportedOptions({
69      CheckstyleConfigGenerator.TARGET_CHECKSTYLE})
70  public class CheckstyleConfigGenerator extends AbstractGenerator {
71  
72    static final String TARGET_CHECKSTYLE = "targetCheckstyle";
73  
74    private Set<String> tagSet = new HashSet<String>();
75  
76    private String targetCheckstyle;
77  
78    @Override
79    public void configure() {
80      final Map<String, String> options = processingEnv.getOptions();
81      targetCheckstyle = options.get(TARGET_CHECKSTYLE);
82  
83      info("Generating the tobago-checkstyle.xml"); // XXX name?
84      info("Options:");
85      info(TARGET_CHECKSTYLE + ": " + targetCheckstyle);
86    }
87  
88    @Override
89    public void generate() throws ParserConfigurationException, IOException, TransformerException,
90        ClassNotFoundException {
91      final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
92      dbf.setValidating(false);
93      final DocumentBuilder parser = dbf.newDocumentBuilder();
94      final Document document = parser.newDocument();
95      final Element module = document.createElement("module");
96      module.setAttribute("name", "Checker");
97  
98      for (final PackageElement packageElement : getPackages()) {
99        final Taglib taglibAnnotation = packageElement.getAnnotation(Taglib.class);
100       createCheckstyleConfig(taglibAnnotation, packageElement, module, document);
101     }
102 
103     document.appendChild(module);
104 
105     writeCheckstyleConfig(document);
106   }
107 
108   private Document createCheckstyleConfig(
109       final Taglib taglibAnnotation, final PackageElement packageElement, final Element module, final Document document)
110       throws ParserConfigurationException, ClassNotFoundException {
111     resetDuplicateList();
112 
113     addLib(taglibAnnotation, module, document);
114 
115     for (final TypeElement typeElement : getTypes()) {
116       if (processingEnv.getElementUtils().getPackageOf(typeElement).equals(packageElement)) {
117         appendTag(typeElement, taglibAnnotation.shortName(), module, document);
118       }
119     }
120     return document;
121   }
122 
123   protected void writeCheckstyleConfig(final Document document) throws IOException, TransformerException {
124     Writer writer = null;
125     try {
126       final String path = "checkstyle-tobago.xml";
127       final String name = (StringUtils.isNotBlank(targetCheckstyle) ? targetCheckstyle + '/' : "") + path;
128       final FileObject resource = processingEnv.getFiler().createResource(StandardLocation.SOURCE_OUTPUT, "", name);
129       info("Writing to file: " + resource.toUri());
130       writer = resource.openWriter();
131 
132       final TransformerFactory transFactory = TransformerFactory.newInstance();
133       transFactory.setAttribute("indent-number", 2);
134       final Transformer transformer = transFactory.newTransformer();
135       transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//Puppy Crawl//DTD Check Configuration 1.2//EN");
136       transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://www.puppycrawl.com/dtds/configuration_1_2.dtd");
137       transformer.setOutputProperty(OutputKeys.INDENT, "yes");
138       transformer.transform(new DOMSource(document), new StreamResult(writer));
139     } finally {
140       IOUtils.closeQuietly(writer);
141     }
142   }
143 
144   protected void appendTag(
145       final TypeElement typeElement, final String taglib, final Element parent, final Document document)
146       throws ClassNotFoundException {
147     final Tag annotationTag = typeElement.getAnnotation(Tag.class);
148     if (annotationTag != null) {
149       checkDuplicates(annotationTag.name());
150       // TODO configure replacement
151       final String className;
152       if (typeElement.getAnnotation(SimpleTag.class) != null || typeElement.getAnnotation(ValidatorTag.class) != null) {
153         className = AnnotationUtils.generatedTagName(typeElement);
154       } else if (typeElement.getAnnotation(ExtensionTag.class) != null) {
155         className = typeElement.getQualifiedName().toString();
156       } else if (typeElement.getAnnotation(UIComponentTag.class) != null) {
157         className = "org.apache.myfaces.tobago.internal.taglib." + StringUtils.capitalize(annotationTag.name())
158             + "Tag";
159       } else {
160         throw new RuntimeException("Not supported: " + typeElement.getQualifiedName());
161       }
162       info("Replacing: " + typeElement.getQualifiedName() + " -> " + className);
163       if (typeElement.getAnnotation(Deprecated.class) != null) {
164         addTag(taglib, parent, annotationTag.name(), document);
165       }
166       addAttributes(typeElement, taglib, parent, annotationTag.name(), document);
167       if (annotationTag.deprecatedName() != null && annotationTag.deprecatedName().length() > 0) {
168         addTag(taglib, parent, annotationTag.deprecatedName(), document);
169         addAttributes(typeElement, taglib, parent, annotationTag.name(), document);
170       }
171     }
172   }
173 
174   protected void addTag(final String taglib, final Element parent, final String tagName, final Document document) {
175 
176     final String format = "<" + taglib + ":" + tagName + "\\b";
177     final String message = "The tag '" + tagName + "' is deprecated.";
178 
179     final Element tag = createRegexpModule(format, message, document);
180 
181     parent.appendChild(tag);
182   }
183 
184   private void checkDuplicates(final String tagName) {
185     if (tagSet.contains(tagName)) {
186       throw new IllegalArgumentException("tag with name " + tagName + " already defined!");
187     } else {
188       tagSet.add(tagName);
189     }
190   }
191 
192   private void resetDuplicateList() {
193     tagSet = new HashSet<String>();
194   }
195 
196   protected void addAttributes(
197       final TypeElement type, final String taglib, final Element tagElement, final String tagName,
198       final Document document)
199       throws ClassNotFoundException {
200 
201     for (final javax.lang.model.element.Element element : getAllMembers(type)) {
202       if (element instanceof ExecutableElement) {
203         final ExecutableElement executableElement = (ExecutableElement) element;
204         if (executableElement.getAnnotation(TagAttribute.class) == null
205             && executableElement.getAnnotation(UIComponentTagAttribute.class) == null) {
206           continue;
207         }
208         addAttribute(executableElement, taglib, tagElement, tagName, document);
209       }
210     }
211   }
212 
213   protected void addAttribute(
214       final ExecutableElement declaration, final String taglib, final Element parent, final String tagName,
215       final Document document) {
216     final TagAttribute tagAttribute = declaration.getAnnotation(TagAttribute.class);
217     final Deprecated deprecatedAnnotation = declaration.getAnnotation(Deprecated.class);
218     if (tagAttribute != null && deprecatedAnnotation != null) {
219       final String simpleName = declaration.getSimpleName().toString();
220       if (simpleName.startsWith("set") || simpleName.startsWith("get")) {
221 
222         String attributeStr = simpleName.substring(3, 4).toLowerCase(Locale.ENGLISH) + simpleName.substring(4);
223         if (tagAttribute.name().length() > 0) {
224           attributeStr = tagAttribute.name();
225         }
226 
227         final String format = "<" + taglib + ":" + tagName + "\\b[^<]*\\b" + attributeStr + "=";
228         final String message = "The attribute '" + attributeStr + "' is deprecated for tag '" + tagName + "'";
229 
230         final Element module = createRegexpModule(format, message, document);
231 
232         parent.appendChild(module);
233       } else {
234         throw new IllegalArgumentException("Only setter allowed found: " + simpleName);
235       }
236     }
237   }
238 
239   private List<? extends javax.lang.model.element.Element> getAllMembers(final TypeElement type) {
240     final List<? extends javax.lang.model.element.Element> members
241         = new ArrayList<javax.lang.model.element.Element>(processingEnv.getElementUtils().getAllMembers(type));
242     Collections.sort(members, new Comparator<javax.lang.model.element.Element>() {
243       @Override
244       public int compare(final javax.lang.model.element.Element d1, final javax.lang.model.element.Element d2) {
245         return d1.getSimpleName().toString().compareTo(d2.getSimpleName().toString());
246       }
247     });
248     return members;
249   }
250 
251   private void addLib(final Taglib taglibAnnotation, final Element parent, final Document document) {
252 
253     final String shortName = taglibAnnotation.shortName();
254     if (shortName.length() != 2) {
255 
256     }
257     final String uri = taglibAnnotation.uri();
258 
259     final String format = "(?<!" + shortName + ")=(\"|')" + uri + "(\"|')";
260     final String message = "The taglib declaration is not like 'xmlns:" + shortName + "=\"" + uri + "\"'";
261 
262     final Element module = createRegexpModule(format, message, document);
263 
264     parent.appendChild(module);
265   }
266 
267   protected Element createRegexpModule(final String formatValue, final String messageValue, final Document document) {
268     final Element module = document.createElement("module");
269     module.setAttribute("name", "RegexpMultiline");
270 
271     final Element format = document.createElement("property");
272     format.setAttribute("name", "format");
273     format.setAttribute("value", formatValue);
274     module.appendChild(format);
275 
276     final Element message = document.createElement("property");
277     message.setAttribute("name", "message");
278     message.setAttribute("value", messageValue);
279     module.appendChild(message);
280 
281     final Element severity = document.createElement("property");
282     severity.setAttribute("name", "severity");
283     severity.setAttribute("value", "warning");
284     module.appendChild(severity);
285 
286     return module;
287   }
288 
289 }