001    /*
002     * Sonar, open source software quality management tool.
003     * Copyright (C) 2008-2011 SonarSource
004     * mailto:contact AT sonarsource DOT com
005     *
006     * Sonar 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     * Sonar 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
017     * License along with Sonar; if not, write to the Free Software
018     * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02
019     */
020    package org.sonar.test.i18n;
021    
022    import com.google.common.collect.Lists;
023    import com.google.common.collect.Maps;
024    import org.apache.commons.io.IOUtils;
025    import org.hamcrest.BaseMatcher;
026    import org.hamcrest.Description;
027    import org.sonar.test.TestUtils;
028    
029    import java.io.*;
030    import java.net.MalformedURLException;
031    import java.net.URL;
032    import java.util.*;
033    
034    import static org.hamcrest.Matchers.is;
035    import static org.hamcrest.Matchers.notNullValue;
036    import static org.junit.Assert.assertThat;
037    import static org.junit.Assert.fail;
038    
039    public class BundleSynchronizedMatcher extends BaseMatcher<String> {
040    
041      public static final String L10N_PATH = "/org/sonar/l10n/";
042      private static final String GITHUB_RAW_FILE_PATH = "https://raw.github.com/SonarSource/sonar/master/plugins/sonar-l10n-en-plugin/src/main/resources/org/sonar/l10n/";
043      private static final Collection<String> CORE_BUNDLES = Lists.newArrayList("checkstyle.properties", "core.properties",
044          "findbugs.properties", "gwt.properties", "pmd.properties", "squidjava.properties");
045    
046      private String sonarVersion;
047      // we use this variable to be able to unit test this class without looking at the real Github core bundles that change all the time
048      private String remote_file_path;
049      private String bundleName;
050      private SortedMap<String, String> missingKeys;
051      private SortedMap<String, String> nonExistingKeys;
052    
053      public BundleSynchronizedMatcher(String sonarVersion) {
054        this(sonarVersion, GITHUB_RAW_FILE_PATH);
055      }
056    
057      public BundleSynchronizedMatcher(String sonarVersion, String remote_file_path) {
058        this.sonarVersion = sonarVersion;
059        this.remote_file_path = remote_file_path;
060      }
061    
062      public boolean matches(Object arg0) {
063        if (!(arg0 instanceof String)) {
064          return false;
065        }
066        bundleName = (String) arg0;
067    
068        // Get the bundle
069        File bundle = getBundleFileFromClasspath(bundleName);
070    
071        // Find the default bundle name which should be compared to
072        String defaultBundleName = extractDefaultBundleName(bundleName);
073        File defaultBundle = null;
074        if (isCoreBundle(defaultBundleName)) {
075          defaultBundle = getBundleFileFromGithub(defaultBundleName);
076        } else {
077          defaultBundle = getBundleFileFromClasspath(defaultBundleName);
078        }
079    
080        // and now let's compare
081        try {
082          missingKeys = retrieveMissingTranslations(bundle, defaultBundle);
083          nonExistingKeys = retrieveMissingTranslations(defaultBundle, bundle);
084          return missingKeys.isEmpty() && nonExistingKeys.isEmpty();
085        } catch (IOException e) {
086          fail("An error occured while reading the bundles: " + e.getMessage());
087          return false;
088        }
089      }
090    
091      public void describeTo(Description description) {
092        // report file
093        File dumpFile = new File("target/l10n/" + bundleName + ".report.txt");
094    
095        // prepare message
096        StringBuilder details = prepareDetailsMessage(dumpFile);
097        description.appendText(details.toString());
098    
099        // print report in target directory
100        printReport(dumpFile, details.toString());
101      }
102    
103      private StringBuilder prepareDetailsMessage(File dumpFile) {
104        StringBuilder details = new StringBuilder("\n=======================\n'");
105        details.append(bundleName);
106        details.append("' is not synchronized.");
107        print("\n\n Missing translations are:", missingKeys, details);
108        print("\n\nThe following translations do not exist in the reference bundle:", nonExistingKeys, details);
109        details.append("\n\nSee report file located at: " + dumpFile.getAbsolutePath());
110        details.append("\n=======================");
111        return details;
112      }
113    
114      private void print(String title, SortedMap<String, String> translations, StringBuilder to) {
115        if (!translations.isEmpty()) {
116          to.append(title);
117          for (Map.Entry<String, String> entry : translations.entrySet()) {
118            to.append("\n").append(entry.getKey()).append("=").append(entry.getValue());
119          }
120        }
121      }
122    
123      private void printReport(File dumpFile, String details) {
124        if (dumpFile.exists()) {
125          dumpFile.delete();
126        }
127        dumpFile.getParentFile().mkdirs();
128        FileWriter writer = null;
129        try {
130          writer = new FileWriter(dumpFile);
131          writer.write(details);
132        } catch (IOException e) {
133          System.out.println("Unable to write the report to 'target/l10n/" + bundleName + ".report.txt'.");
134        } finally {
135          IOUtils.closeQuietly(writer);
136        }
137      }
138    
139      protected SortedMap<String, String> retrieveMissingTranslations(File bundle, File referenceBundle) throws IOException {
140        SortedMap<String, String> missingKeys = Maps.newTreeMap();
141    
142        Properties bundleProps = loadProperties(bundle);
143        Properties referenceProperties = loadProperties(referenceBundle);
144    
145        for (Map.Entry<Object, Object> entry : referenceProperties.entrySet()) {
146          String key = (String) entry.getKey();
147          if (!bundleProps.containsKey(key)) {
148            missingKeys.put(key, (String) entry.getValue());
149          }
150        }
151    
152        return missingKeys;
153      }
154    
155      private Properties loadProperties(File f) throws IOException {
156        Properties props = new Properties();
157        FileInputStream input = new FileInputStream(f);
158        try {
159          props.load(input);
160          return props;
161          
162        } finally {
163          IOUtils.closeQuietly(input);
164        }
165      }
166    
167      protected File getBundleFileFromGithub(String defaultBundleName) {
168        File localBundle = new File("target/l10n/download/" + defaultBundleName);
169        try {
170          String remoteFile = computeGitHubURL(defaultBundleName, sonarVersion);
171          saveUrlToLocalFile(remoteFile, localBundle);
172        } catch (MalformedURLException e) {
173          fail("Could not download the original core bundle at: " + remote_file_path + defaultBundleName);
174        } catch (IOException e) {
175          fail("Could not download the original core bundle at: " + remote_file_path + defaultBundleName);
176        }
177        assertThat("File 'target/tmp/" + defaultBundleName + "' has been downloaded but does not exist.", localBundle, notNullValue());
178        assertThat("File 'target/tmp/" + defaultBundleName + "' has been downloaded but does not exist.", localBundle.exists(), is(true));
179        return localBundle;
180      }
181    
182      protected String computeGitHubURL(String defaultBundleName, String sonarVersion) {
183        String computedURL = remote_file_path + defaultBundleName;
184        if (sonarVersion != null && !sonarVersion.contains("-SNAPSHOT")) {
185          computedURL = computedURL.replace("/master/", "/" + sonarVersion + "/");
186        }
187        return computedURL;
188      }
189    
190      protected File getBundleFileFromClasspath(String bundleName) {
191        File bundle = TestUtils.getResource(L10N_PATH + bundleName);
192        assertThat("File '" + bundleName + "' does not exist in '/org/sonar/l10n/'.", bundle, notNullValue());
193        assertThat("File '" + bundleName + "' does not exist in '/org/sonar/l10n/'.", bundle.exists(), is(true));
194        return bundle;
195      }
196    
197      protected String extractDefaultBundleName(String bundleName) {
198        int firstUnderScoreIndex = bundleName.indexOf('_');
199        assertThat("The bundle '" + bundleName + "' is a default bundle (without locale), so it can't be compared.", firstUnderScoreIndex > 0,
200            is(true));
201        return bundleName.substring(0, firstUnderScoreIndex) + ".properties";
202      }
203    
204      protected boolean isCoreBundle(String defaultBundleName) {
205        return CORE_BUNDLES.contains(defaultBundleName);
206      }
207    
208      private void saveUrlToLocalFile(String url, File localFile) throws MalformedURLException, IOException {
209        if (localFile.exists()) {
210          localFile.delete();
211        }
212        localFile.getParentFile().mkdirs();
213    
214        BufferedInputStream in = null;
215        FileOutputStream fout = null;
216        try {
217          in = new BufferedInputStream(new URL(url).openStream());
218          fout = new FileOutputStream(localFile);
219    
220          byte data[] = new byte[1024];
221          int count;
222          while ((count = in.read(data, 0, 1024)) != -1) {
223            fout.write(data, 0, count);
224          }
225        } finally {
226          if (in != null)
227            in.close();
228          if (fout != null)
229            fout.close();
230        }
231      }
232    
233    }