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    public void configure() {
79      final Map<String, String> options = processingEnv.getOptions();
80      targetCheckstyle = options.get(TARGET_CHECKSTYLE);
81  
82      info("Generating the tobago-checkstyle.xml"); // XXX name?
83      info("Options:");
84      info(TARGET_CHECKSTYLE + ": " + targetCheckstyle);
85    }
86  
87    public void generate() throws ParserConfigurationException, IOException, TransformerException,
88        ClassNotFoundException {
89      final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
90      dbf.setValidating(false);
91      final DocumentBuilder parser = dbf.newDocumentBuilder();
92      final Document document = parser.newDocument();
93      final Element module = document.createElement("module");
94      module.setAttribute("name", "Checker");
95  
96      for (final PackageElement packageElement : getPackages()) {
97        final Taglib taglibAnnotation = packageElement.getAnnotation(Taglib.class);
98        createCheckstyleConfig(taglibAnnotation, packageElement, module, document);
99      }
100 
101     document.appendChild(module);
102 
103     writeCheckstyleConfig(document);
104   }
105 
106   private Document createCheckstyleConfig(
107       final Taglib taglibAnnotation, final PackageElement packageElement, final Element module, final Document document)
108       throws ParserConfigurationException, ClassNotFoundException {
109     resetDuplicateList();
110 
111     addLib(taglibAnnotation, module, document);
112 
113     for (final TypeElement typeElement : getTypes()) {
114       if (processingEnv.getElementUtils().getPackageOf(typeElement).equals(packageElement)) {
115         appendTag(typeElement, taglibAnnotation.shortName(), module, document);
116       }
117     }
118     return document;
119   }
120 
121   protected void writeCheckstyleConfig(final Document document) throws IOException, TransformerException {
122     Writer writer = null;
123     try {
124       final String path = "checkstyle-tobago.xml";
125       final String name = (StringUtils.isNotBlank(targetCheckstyle) ? targetCheckstyle + '/' : "") + path;
126       final FileObject resource = processingEnv.getFiler().createResource(StandardLocation.SOURCE_OUTPUT, "", name);
127       info("Writing to file: " + resource.toUri());
128       writer = resource.openWriter();
129 
130       final TransformerFactory transFactory = TransformerFactory.newInstance();
131       transFactory.setAttribute("indent-number", 2);
132       final Transformer transformer = transFactory.newTransformer();
133       transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//Puppy Crawl//DTD Check Configuration 1.2//EN");
134       transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://www.puppycrawl.com/dtds/configuration_1_2.dtd");
135       transformer.setOutputProperty(OutputKeys.INDENT, "yes");
136       transformer.transform(new DOMSource(document), new StreamResult(writer));
137     } finally {
138       IOUtils.closeQuietly(writer);
139     }
140   }
141 
142   protected void appendTag(
143       final TypeElement typeElement, final String taglib, final Element parent, final Document document)
144       throws ClassNotFoundException {
145     final Tag annotationTag = typeElement.getAnnotation(Tag.class);
146     if (annotationTag != null) {
147       checkDuplicates(annotationTag.name());
148       // TODO configure replacement
149       final String className;
150       if (typeElement.getAnnotation(SimpleTag.class) != null || typeElement.getAnnotation(ValidatorTag.class) != null) {
151         className = AnnotationUtils.generatedTagName(typeElement);
152       } else if (typeElement.getAnnotation(ExtensionTag.class) != null) {
153         className = typeElement.getQualifiedName().toString();
154       } else if (typeElement.getAnnotation(UIComponentTag.class) != null) {
155         className = "org.apache.myfaces.tobago.internal.taglib." + StringUtils.capitalize(annotationTag.name())
156             + "Tag";
157       } else {
158         throw new RuntimeException("Not supported: " + typeElement.getQualifiedName());
159       }
160       info("Replacing: " + typeElement.getQualifiedName() + " -> " + className);
161       if (typeElement.getAnnotation(Deprecated.class) != null) {
162         addTag(taglib, parent, annotationTag.name(), document);
163       }
164       addAttributes(typeElement, taglib, parent, annotationTag.name(), document);
165       if (annotationTag.deprecatedName() != null && annotationTag.deprecatedName().length() > 0) {
166         addTag(taglib, parent, annotationTag.deprecatedName(), document);
167         addAttributes(typeElement, taglib, parent, annotationTag.name(), document);
168       }
169     }
170   }
171 
172   protected void addTag(final String taglib, final Element parent, final String tagName, final Document document) {
173 
174     final String format = "<" + taglib + ":" + tagName + "\\b";
175     final String message = "The tag '" + tagName + "' is deprecated.";
176 
177     final Element tag = createRegexpModule(format, message, document);
178 
179     parent.appendChild(tag);
180   }
181 
182   private void checkDuplicates(final String tagName) {
183     if (tagSet.contains(tagName)) {
184       throw new IllegalArgumentException("tag with name " + tagName + " already defined!");
185     } else {
186       tagSet.add(tagName);
187     }
188   }
189 
190   private void resetDuplicateList() {
191     tagSet = new HashSet<String>();
192   }
193 
194   protected void addAttributes(
195       final TypeElement type, final String taglib, final Element tagElement, final String tagName,
196       final Document document)
197       throws ClassNotFoundException {
198 
199     for (final javax.lang.model.element.Element element : getAllMembers(type)) {
200       if (element instanceof ExecutableElement) {
201         final ExecutableElement executableElement = (ExecutableElement) element;
202         if (executableElement.getAnnotation(TagAttribute.class) == null
203             && executableElement.getAnnotation(UIComponentTagAttribute.class) == null) {
204           continue;
205         }
206         addAttribute(executableElement, taglib, tagElement, tagName, document);
207       }
208     }
209   }
210 
211   protected void addAttribute(
212       final ExecutableElement declaration, final String taglib, final Element parent, final String tagName,
213       final Document document) {
214     final TagAttribute tagAttribute = declaration.getAnnotation(TagAttribute.class);
215     final Deprecated deprecatedAnnotation = declaration.getAnnotation(Deprecated.class);
216     if (tagAttribute != null && deprecatedAnnotation != null) {
217       final String simpleName = declaration.getSimpleName().toString();
218       if (simpleName.startsWith("set") || simpleName.startsWith("get")) {
219 
220         String attributeStr = simpleName.substring(3, 4).toLowerCase(Locale.ENGLISH) + simpleName.substring(4);
221         if (tagAttribute.name().length() > 0) {
222           attributeStr = tagAttribute.name();
223         }
224 
225         final String format = "<" + taglib + ":" + tagName + "\\b[^<]*\\b" + attributeStr + "=";
226         final String message = "The attribute '" + attributeStr + "' is deprecated for tag '" + tagName + "'";
227 
228         final Element module = createRegexpModule(format, message, document);
229 
230         parent.appendChild(module);
231       } else {
232         throw new IllegalArgumentException("Only setter allowed found: " + simpleName);
233       }
234     }
235   }
236 
237   private List<? extends javax.lang.model.element.Element> getAllMembers(final TypeElement type) {
238     final List<? extends javax.lang.model.element.Element> members
239         = new ArrayList<javax.lang.model.element.Element>(processingEnv.getElementUtils().getAllMembers(type));
240     Collections.sort(members, new Comparator<javax.lang.model.element.Element>() {
241       public int compare(final javax.lang.model.element.Element d1, final javax.lang.model.element.Element d2) {
242         return d1.getSimpleName().toString().compareTo(d2.getSimpleName().toString());
243       }
244     });
245     return members;
246   }
247 
248   private void addLib(final Taglib taglibAnnotation, final Element parent, final Document document) {
249 
250     final String shortName = taglibAnnotation.shortName();
251     if (shortName.length() != 2) {
252 
253     }
254     final String uri = taglibAnnotation.uri();
255 
256     final String format = "(?<!" + shortName + ")=(\"|')" + uri + "(\"|')";
257     final String message = "The taglib declaration is not like 'xmlns:" + shortName + "=\"" + uri + "\"'";
258 
259     final Element module = createRegexpModule(format, message, document);
260 
261     parent.appendChild(module);
262   }
263 
264   protected Element createRegexpModule(final String formatValue, final String messageValue, final Document document) {
265     final Element module = document.createElement("module");
266     module.setAttribute("name", "RegexpMultiline");
267 
268     final Element format = document.createElement("property");
269     format.setAttribute("name", "format");
270     format.setAttribute("value", formatValue);
271     module.appendChild(format);
272 
273     final Element message = document.createElement("property");
274     message.setAttribute("name", "message");
275     message.setAttribute("value", messageValue);
276     module.appendChild(message);
277 
278     final Element severity = document.createElement("property");
279     severity.setAttribute("name", "severity");
280     severity.setAttribute("value", "warning");
281     module.appendChild(severity);
282 
283     return module;
284   }
285 
286 }