001    /*
002     * SonarQube, open source software quality management tool.
003     * Copyright (C) 2008-2014 SonarSource
004     * mailto:contact AT sonarsource DOT com
005     *
006     * SonarQube is free software; you can redistribute it and/or
007     * modify it under the terms of the GNU Lesser General Public
008     * License as published by the Free Software Foundation; either
009     * version 3 of the License, or (at your option) any later version.
010     *
011     * SonarQube is distributed in the hope that it will be useful,
012     * but WITHOUT ANY WARRANTY; without even the implied warranty of
013     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
014     * Lesser General Public License for more details.
015     *
016     * You should have received a copy of the GNU Lesser General Public License
017     * along with this program; if not, write to the Free Software Foundation,
018     * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
019     */
020    package org.sonar.api.batch.rule;
021    
022    import com.google.common.collect.Maps;
023    import org.apache.commons.lang.StringUtils;
024    import org.sonar.api.rule.RuleKey;
025    import org.sonar.api.utils.AnnotationUtils;
026    import org.sonar.api.utils.FieldUtils2;
027    import org.sonar.api.utils.SonarException;
028    import org.sonar.check.RuleProperty;
029    
030    import javax.annotation.CheckForNull;
031    import java.lang.reflect.Field;
032    import java.util.Arrays;
033    import java.util.Collection;
034    import java.util.List;
035    import java.util.Map;
036    
037    /**
038     * Instantiates checks (objects that provide implementation of coding
039     * rules) that use sonar-check-api annotations. Checks are selected and configured
040     * from the Quality profiles enabled on the current module.
041     * <p/>
042     * Example of check class:
043     * <pre>
044     *   {@literal @}org.sonar.check.Rule(key = "S001")
045     *   public class CheckS001 {
046     *     {@literal @}org.sonar.check.RuleProperty
047     *     private String pattern;
048     *
049     *     public String getPattern() {
050     *       return pattern;
051     *     }
052     * }
053     * </pre>
054     * How to use:
055     * <pre>
056     *   public class MyRuleEngine extends BatchExtension {
057     *     private final CheckFactory checkFactory;
058     *
059     *     public MyRuleEngine(CheckFactory checkFactory) {
060     *       this.checkFactory = checkFactory;
061     *     }
062     *
063     *     public void execute() {
064     *       Checks checks = checkFactory.create("my-rule-repository");
065     *       checks.addAnnotatedChecks(CheckS001.class);
066     *       // checks.all() contains an instance of CheckS001
067     *       // with field "pattern" set to the value specified in
068     *       // the Quality profile
069     *
070     *       // Checks are used to detect issues on source code
071     *
072     *       // checks.ruleKey(obj) can be used to create the related issues
073     *     }
074     *   }
075     * </pre>
076     * <p/>
077     * It replaces org.sonar.api.checks.AnnotationCheckFactory
078     *
079     * @since 4.2
080     */
081    public class Checks<C> {
082      private final ActiveRules activeRules;
083      private final String repository;
084      private final Map<RuleKey, C> checkByRule = Maps.newHashMap();
085      private final Map<C, RuleKey> ruleByCheck = Maps.newIdentityHashMap();
086    
087      Checks(ActiveRules activeRules, String repository) {
088        this.activeRules = activeRules;
089        this.repository = repository;
090      }
091    
092      @CheckForNull
093      public C of(RuleKey ruleKey) {
094        return checkByRule.get(ruleKey);
095      }
096    
097      public Collection<C> all() {
098        return checkByRule.values();
099      }
100    
101      @CheckForNull
102      public RuleKey ruleKey(C check) {
103        return ruleByCheck.get(check);
104      }
105    
106      private void add(RuleKey ruleKey, C obj) {
107        checkByRule.put(ruleKey, obj);
108        ruleByCheck.put(obj, ruleKey);
109      }
110    
111      public Checks<C> addAnnotatedChecks(Object... checkClassesOrObjects) {
112        return addAnnotatedChecks(Arrays.asList(checkClassesOrObjects));
113      }
114    
115      public Checks<C> addAnnotatedChecks(Collection checkClassesOrObjects) {
116        Map<String, Object> checksByEngineKey = Maps.newHashMap();
117        for (Object checkClassesOrObject : checkClassesOrObjects) {
118          String engineKey = annotatedEngineKey(checkClassesOrObject);
119          if (engineKey != null) {
120            checksByEngineKey.put(engineKey, checkClassesOrObject);
121          }
122        }
123    
124        for (ActiveRule activeRule : activeRules.findByRepository(repository)) {
125          String engineKey = StringUtils.defaultIfBlank(activeRule.internalKey(), activeRule.ruleKey().rule());
126          Object checkClassesOrObject = checksByEngineKey.get(engineKey);
127          Object obj = instantiate(activeRule, checkClassesOrObject);
128          add(activeRule.ruleKey(), (C) obj);
129        }
130        return this;
131      }
132    
133      private String annotatedEngineKey(Object annotatedClassOrObject) {
134        String key = null;
135        org.sonar.check.Rule ruleAnnotation = AnnotationUtils.getAnnotation(annotatedClassOrObject, org.sonar.check.Rule.class);
136        if (ruleAnnotation != null) {
137          key = ruleAnnotation.key();
138        }
139        Class clazz = annotatedClassOrObject.getClass();
140        if (annotatedClassOrObject instanceof Class) {
141          clazz = (Class) annotatedClassOrObject;
142        }
143        return StringUtils.defaultIfEmpty(key, clazz.getCanonicalName());
144      }
145    
146      private Object instantiate(ActiveRule activeRule, Object checkClassOrInstance) {
147        try {
148          Object check = checkClassOrInstance;
149          if (check instanceof Class) {
150            check = ((Class) checkClassOrInstance).newInstance();
151          }
152          configureFields(activeRule, check);
153          return check;
154        } catch (InstantiationException e) {
155          throw failToInstantiateCheck(activeRule, checkClassOrInstance, e);
156        } catch (IllegalAccessException e) {
157          throw failToInstantiateCheck(activeRule, checkClassOrInstance, e);
158        }
159      }
160    
161      private RuntimeException failToInstantiateCheck(ActiveRule activeRule, Object checkClassOrInstance, Exception e) {
162        throw new IllegalStateException(String.format("Fail to instantiate class %s for rule %s", checkClassOrInstance, activeRule.ruleKey()), e);
163      }
164    
165      private void configureFields(ActiveRule activeRule, Object check) {
166        for (Map.Entry<String, String> param : activeRule.params().entrySet()) {
167          Field field = getField(check, param.getKey());
168          if (field == null) {
169            throw new IllegalStateException(
170              String.format("The field '%s' does not exist or is not annotated with @RuleProperty in the class %s", param.getKey(), check.getClass().getName()));
171          }
172          if (StringUtils.isNotBlank(param.getValue())) {
173            configureField(check, field, param.getValue());
174          }
175        }
176      }
177    
178      @CheckForNull
179      private Field getField(Object check, String key) {
180        List<Field> fields = FieldUtils2.getFields(check.getClass(), true);
181        for (Field field : fields) {
182          RuleProperty propertyAnnotation = field.getAnnotation(RuleProperty.class);
183          if (propertyAnnotation != null && (StringUtils.equals(key, field.getName()) || StringUtils.equals(key, propertyAnnotation.key()))) {
184            return field;
185          }
186        }
187        return null;
188      }
189    
190      private void configureField(Object check, Field field, String value) {
191        try {
192          field.setAccessible(true);
193    
194          if (field.getType().equals(String.class)) {
195            field.set(check, value);
196    
197          } else if ("int".equals(field.getType().getSimpleName())) {
198            field.setInt(check, Integer.parseInt(value));
199    
200          } else if ("short".equals(field.getType().getSimpleName())) {
201            field.setShort(check, Short.parseShort(value));
202    
203          } else if ("long".equals(field.getType().getSimpleName())) {
204            field.setLong(check, Long.parseLong(value));
205    
206          } else if ("double".equals(field.getType().getSimpleName())) {
207            field.setDouble(check, Double.parseDouble(value));
208    
209          } else if ("boolean".equals(field.getType().getSimpleName())) {
210            field.setBoolean(check, Boolean.parseBoolean(value));
211    
212          } else if ("byte".equals(field.getType().getSimpleName())) {
213            field.setByte(check, Byte.parseByte(value));
214    
215          } else if (field.getType().equals(Integer.class)) {
216            field.set(check, Integer.parseInt(value));
217    
218          } else if (field.getType().equals(Long.class)) {
219            field.set(check, Long.parseLong(value));
220    
221          } else if (field.getType().equals(Double.class)) {
222            field.set(check, Double.parseDouble(value));
223    
224          } else if (field.getType().equals(Boolean.class)) {
225            field.set(check, Boolean.parseBoolean(value));
226    
227          } else {
228            throw new SonarException("The type of the field " + field + " is not supported: " + field.getType());
229          }
230        } catch (IllegalAccessException e) {
231          throw new SonarException("Can not set the value of the field " + field + " in the class: " + check.getClass().getName(), e);
232        }
233      }
234    }