Coverage Report - com.puppycrawl.tools.checkstyle.checks.TranslationCheck
 
Classes in this File Line Coverage Branch Coverage Complexity
TranslationCheck
84%
71/84
86%
19/22
2.2
 
 1  
 ////////////////////////////////////////////////////////////////////////////////
 2  
 // checkstyle: Checks Java source code for adherence to a set of rules.
 3  
 // Copyright (C) 2001-2014  Oliver Burn
 4  
 //
 5  
 // This library is free software; you can redistribute it and/or
 6  
 // modify it under the terms of the GNU Lesser General Public
 7  
 // License as published by the Free Software Foundation; either
 8  
 // version 2.1 of the License, or (at your option) any later version.
 9  
 //
 10  
 // This library is distributed in the hope that it will be useful,
 11  
 // but WITHOUT ANY WARRANTY; without even the implied warranty of
 12  
 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 13  
 // Lesser General Public License for more details.
 14  
 //
 15  
 // You should have received a copy of the GNU Lesser General Public
 16  
 // License along with this library; if not, write to the Free Software
 17  
 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 18  
 ////////////////////////////////////////////////////////////////////////////////
 19  
 package com.puppycrawl.tools.checkstyle.checks;
 20  
 
 21  
 import com.google.common.collect.Lists;
 22  
 import com.google.common.collect.Maps;
 23  
 import com.google.common.collect.Sets;
 24  
 import com.puppycrawl.tools.checkstyle.Defn;
 25  
 import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck;
 26  
 import com.puppycrawl.tools.checkstyle.api.LocalizedMessage;
 27  
 import com.puppycrawl.tools.checkstyle.api.MessageDispatcher;
 28  
 import com.puppycrawl.tools.checkstyle.api.Utils;
 29  
 import java.io.File;
 30  
 import java.io.FileInputStream;
 31  
 import java.io.FileNotFoundException;
 32  
 import java.io.IOException;
 33  
 import java.io.InputStream;
 34  
 import java.util.Enumeration;
 35  
 import java.util.List;
 36  
 import java.util.Map;
 37  
 import java.util.Properties;
 38  
 import java.util.Set;
 39  
 import java.util.TreeSet;
 40  
 import java.util.Map.Entry;
 41  
 
 42  
 /**
 43  
  * <p>
 44  
  * The TranslationCheck class helps to ensure the correct translation of code by
 45  
  * checking property files for consistency regarding their keys.
 46  
  * Two property files describing one and the same context are consistent if they
 47  
  * contain the same keys.
 48  
  * </p>
 49  
  * <p>
 50  
  * An example of how to configure the check is:
 51  
  * </p>
 52  
  * <pre>
 53  
  * &lt;module name="Translation"/&gt;
 54  
  * </pre>
 55  
  * @author Alexandra Bunge
 56  
  * @author lkuehne
 57  
  */
 58  
 public class TranslationCheck
 59  
     extends AbstractFileSetCheck
 60  
 {
 61  
     /** The property files to process. */
 62  1
     private final List<File> mPropertyFiles = Lists.newArrayList();
 63  
 
 64  
     /**
 65  
      * Creates a new <code>TranslationCheck</code> instance.
 66  
      */
 67  
     public TranslationCheck()
 68  1
     {
 69  1
         setFileExtensions(new String[]{"properties"});
 70  1
     }
 71  
 
 72  
     @Override
 73  
     public void beginProcessing(String aCharset)
 74  
     {
 75  1
         super.beginProcessing(aCharset);
 76  1
         mPropertyFiles.clear();
 77  1
     }
 78  
 
 79  
     @Override
 80  
     protected void processFiltered(File aFile, List<String> aLines)
 81  
     {
 82  2
         mPropertyFiles.add(aFile);
 83  2
     }
 84  
 
 85  
     @Override
 86  
     public void finishProcessing()
 87  
     {
 88  1
         super.finishProcessing();
 89  1
         final Map<String, Set<File>> propFilesMap =
 90  
             arrangePropertyFiles(mPropertyFiles);
 91  1
         checkPropertyFileSets(propFilesMap);
 92  1
     }
 93  
 
 94  
     /**
 95  
      * Gets the basename (the unique prefix) of a property file. For example
 96  
      * "xyz/messages" is the basename of "xyz/messages.properties",
 97  
      * "xyz/messages_de_AT.properties", "xyz/messages_en.properties", etc.
 98  
      *
 99  
      * @param aFile the file
 100  
      * @return the extracted basename
 101  
      */
 102  
     private static String extractPropertyIdentifier(final File aFile)
 103  
     {
 104  2
         final String filePath = aFile.getPath();
 105  2
         final int dirNameEnd = filePath.lastIndexOf(File.separatorChar);
 106  2
         final int baseNameStart = dirNameEnd + 1;
 107  2
         final int underscoreIdx = filePath.indexOf('_', baseNameStart);
 108  2
         final int dotIdx = filePath.indexOf('.', baseNameStart);
 109  2
         final int cutoffIdx = (underscoreIdx != -1) ? underscoreIdx : dotIdx;
 110  2
         return filePath.substring(0, cutoffIdx);
 111  
     }
 112  
 
 113  
     /**
 114  
      * Arranges a set of property files by their prefix.
 115  
      * The method returns a Map object. The filename prefixes
 116  
      * work as keys each mapped to a set of files.
 117  
      * @param aPropFiles the set of property files
 118  
      * @return a Map object which holds the arranged property file sets
 119  
      */
 120  
     private static Map<String, Set<File>> arrangePropertyFiles(
 121  
         List<File> aPropFiles)
 122  
     {
 123  1
         final Map<String, Set<File>> propFileMap = Maps.newHashMap();
 124  
 
 125  1
         for (final File f : aPropFiles) {
 126  2
             final String identifier = extractPropertyIdentifier(f);
 127  
 
 128  2
             Set<File> fileSet = propFileMap.get(identifier);
 129  2
             if (fileSet == null) {
 130  1
                 fileSet = Sets.newHashSet();
 131  1
                 propFileMap.put(identifier, fileSet);
 132  
             }
 133  2
             fileSet.add(f);
 134  2
         }
 135  1
         return propFileMap;
 136  
     }
 137  
 
 138  
     /**
 139  
      * Loads the keys of the specified property file into a set.
 140  
      * @param aFile the property file
 141  
      * @return a Set object which holds the loaded keys
 142  
      */
 143  
     private Set<Object> loadKeys(File aFile)
 144  
     {
 145  2
         final Set<Object> keys = Sets.newHashSet();
 146  2
         InputStream inStream = null;
 147  
 
 148  
         try {
 149  
             // Load file and properties.
 150  2
             inStream = new FileInputStream(aFile);
 151  2
             final Properties props = new Properties();
 152  2
             props.load(inStream);
 153  
 
 154  
             // Gather the keys and put them into a set
 155  2
             final Enumeration<?> e = props.propertyNames();
 156  7
             while (e.hasMoreElements()) {
 157  5
                 keys.add(e.nextElement());
 158  
             }
 159  
         }
 160  0
         catch (final IOException e) {
 161  0
             logIOException(e, aFile);
 162  
         }
 163  
         finally {
 164  2
             Utils.closeQuietly(inStream);
 165  2
         }
 166  2
         return keys;
 167  
     }
 168  
 
 169  
     /**
 170  
      * helper method to log an io exception.
 171  
      * @param aEx the exception that occured
 172  
      * @param aFile the file that could not be processed
 173  
      */
 174  
     private void logIOException(IOException aEx, File aFile)
 175  
     {
 176  0
         String[] args = null;
 177  0
         String key = "general.fileNotFound";
 178  0
         if (!(aEx instanceof FileNotFoundException)) {
 179  0
             args = new String[] {aEx.getMessage()};
 180  0
             key = "general.exception";
 181  
         }
 182  0
         final LocalizedMessage message =
 183  
             new LocalizedMessage(
 184  
                 0,
 185  
                 Defn.CHECKSTYLE_BUNDLE,
 186  
                 key,
 187  
                 args,
 188  
                 getId(),
 189  
                 this.getClass(), null);
 190  0
         final TreeSet<LocalizedMessage> messages = Sets.newTreeSet();
 191  0
         messages.add(message);
 192  0
         getMessageDispatcher().fireErrors(aFile.getPath(), messages);
 193  0
         Utils.getExceptionLogger().debug("IOException occured.", aEx);
 194  0
     }
 195  
 
 196  
 
 197  
     /**
 198  
      * Compares the key sets of the given property files (arranged in a map)
 199  
      * with the specified key set. All missing keys are reported.
 200  
      * @param aKeys the set of keys to compare with
 201  
      * @param aFileMap a Map from property files to their key sets
 202  
      */
 203  
     private void compareKeySets(Set<Object> aKeys,
 204  
             Map<File, Set<Object>> aFileMap)
 205  
     {
 206  1
         final Set<Entry<File, Set<Object>>> fls = aFileMap.entrySet();
 207  
 
 208  1
         for (Entry<File, Set<Object>> entry : fls) {
 209  2
             final File currentFile = entry.getKey();
 210  2
             final MessageDispatcher dispatcher = getMessageDispatcher();
 211  2
             final String path = currentFile.getPath();
 212  2
             dispatcher.fireFileStarted(path);
 213  2
             final Set<Object> currentKeys = entry.getValue();
 214  
 
 215  
             // Clone the keys so that they are not lost
 216  2
             final Set<Object> keysClone = Sets.newHashSet(aKeys);
 217  2
             keysClone.removeAll(currentKeys);
 218  
 
 219  
             // Remaining elements in the key set are missing in the current file
 220  2
             if (!keysClone.isEmpty()) {
 221  1
                 for (Object key : keysClone) {
 222  1
                     log(0, "translation.missingKey", key);
 223  
                 }
 224  
             }
 225  2
             fireErrors(path);
 226  2
             dispatcher.fireFileFinished(path);
 227  2
         }
 228  1
     }
 229  
 
 230  
 
 231  
     /**
 232  
      * Tests whether the given property files (arranged by their prefixes
 233  
      * in a Map) contain the proper keys.
 234  
      *
 235  
      * Each group of files must have the same keys. If this is not the case
 236  
      * an error message is posted giving information which key misses in
 237  
      * which file.
 238  
      *
 239  
      * @param aPropFiles the property files organized as Map
 240  
      */
 241  
     private void checkPropertyFileSets(Map<String, Set<File>> aPropFiles)
 242  
     {
 243  1
         final Set<Entry<String, Set<File>>> entrySet = aPropFiles.entrySet();
 244  
 
 245  1
         for (Entry<String, Set<File>> entry : entrySet) {
 246  1
             final Set<File> files = entry.getValue();
 247  
 
 248  1
             if (files.size() >= 2) {
 249  
                 // build a map from files to the keys they contain
 250  1
                 final Set<Object> keys = Sets.newHashSet();
 251  1
                 final Map<File, Set<Object>> fileMap = Maps.newHashMap();
 252  
 
 253  1
                 for (File file : files) {
 254  2
                     final Set<Object> fileKeys = loadKeys(file);
 255  2
                     keys.addAll(fileKeys);
 256  2
                     fileMap.put(file, fileKeys);
 257  2
                 }
 258  
 
 259  
                 // check the map for consistency
 260  1
                 compareKeySets(keys, fileMap);
 261  
             }
 262  1
         }
 263  1
     }
 264  
 }