summaryrefslogtreecommitdiff
path: root/src/plugins/preflighting.checkers/src/com/motorolamobility/preflighting/checkers/localizationStrings/MissingValueCondition.java
blob: 380373b14f2e262c84cbd0f40d144356e675976a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.motorolamobility.preflighting.checkers.localizationStrings;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

import org.eclipse.core.runtime.IStatus;

import com.motorolamobility.preflighting.checkers.CheckerPlugin;
import com.motorolamobility.preflighting.checkers.i18n.CheckerNLS;
import com.motorolamobility.preflighting.core.applicationdata.ApplicationData;
import com.motorolamobility.preflighting.core.applicationdata.ResourcesFolderElement;
import com.motorolamobility.preflighting.core.applicationdata.StringsElement;
import com.motorolamobility.preflighting.core.checker.condition.CanExecuteConditionStatus;
import com.motorolamobility.preflighting.core.checker.condition.Condition;
import com.motorolamobility.preflighting.core.checker.condition.ICondition;
import com.motorolamobility.preflighting.core.devicespecification.DeviceSpecification;
import com.motorolamobility.preflighting.core.exception.PreflightingCheckerException;
import com.motorolamobility.preflighting.core.internal.cond.utils.ConditionUtils;
import com.motorolamobility.preflighting.core.validation.ValidationManagerConfiguration;
import com.motorolamobility.preflighting.core.validation.ValidationResult;
import com.motorolamobility.preflighting.core.validation.ValidationResultData;

/**
 * Check if there are keys with empty values.
 *
 */
public class MissingValueCondition extends Condition implements ICondition
{
    private LocalizationStringsChecker checker;

    private ValidationManagerConfiguration valManagerConfig;

    private ResourcesFolderElement resFolder;

    private Locale defaultLocale;

    /**
     * The string element for the default locale
     */
    StringsElement stringsKeysDefault;

    /**
     * Check if there is at least one string key defined in default or alternate locales.
     * @see com.motorolamobility.preflighting.core.checker.condition.Condition#canExecute(com.motorolamobility.preflighting.core.applicationdata.ApplicationData, java.util.List)
     */
    @Override
    public CanExecuteConditionStatus canExecute(ApplicationData data,
            List<DeviceSpecification> deviceSpecs) throws PreflightingCheckerException
    {
        CanExecuteConditionStatus status;

        this.checker = (LocalizationStringsChecker) getChecker();
        this.resFolder = checker.getResourcesFolder();
        this.stringsKeysDefault = checker.getStringsKeysDefault();

        List<Locale> availableLocales = resFolder.getAvailableLocales();

        //check if there is at least one key in default or non-default locales 
        if ((stringsKeysDefault != null) && (stringsKeysDefault.getKeyList() != null)
                && (stringsKeysDefault.getKeyList().size() > 0))
        {
            //at least one string key found at stringsKeyDefault 
            status = new CanExecuteConditionStatus(IStatus.OK, CheckerPlugin.PLUGIN_ID, ""); //$NON-NLS-1$
            status.setConditionId(getId());
        }
        else if ((availableLocales != null) && (availableLocales.size() > 0))
        {
            //default locale has no string key defined
            //look for string keys in non-default languages
            boolean nonDefaultLanguageStringKeyFound = false;

            for (Locale locale : availableLocales)
            {
                if (resFolder.getValuesElement(locale).getKeyList().size() > 0)
                {
                    nonDefaultLanguageStringKeyFound = true;
                    break;
                }
            }

            if (nonDefaultLanguageStringKeyFound)
            {
                //at least one string key found in non default languages (availableLocales) 
                status = new CanExecuteConditionStatus(IStatus.OK, CheckerPlugin.PLUGIN_ID, ""); //$NON-NLS-1$
                status.setConditionId(getId());
            }
            else
            {
                //both default and non-default localization files are empty
                status =
                        new CanExecuteConditionStatus(
                                IStatus.ERROR,
                                CheckerPlugin.PLUGIN_ID,
                                CheckerNLS
                                        .bind(CheckerNLS.LocalizationStringsChecker_conditionMissingValue_CouldNotBeRun_EmptyLocalizationFiles,
                                                getId()));
                status.setConditionId(getId());
            }
        }
        else
        {
            //default localization file is empty and there is no non-default locale set
            status =
                    new CanExecuteConditionStatus(
                            IStatus.ERROR,
                            CheckerPlugin.PLUGIN_ID,
                            CheckerNLS
                                    .bind(CheckerNLS.LocalizationStringsChecker_conditionMissingValue_CouldNotBeRun_EmptyLocalizationFiles,
                                            getId()));
            status.setConditionId(getId());
        }

        return status;
    }

    /**
     * Check if there are keys with empty values in default and alternate locales.  
     * @see com.motorolamobility.preflighting.core.checker.condition.Condition#execute(com.motorolamobility.preflighting.core.applicationdata.ApplicationData, java.util.List, com.motorolamobility.preflighting.core.validation.ValidationManagerConfiguration, com.motorolamobility.preflighting.core.validation.ValidationResult)
     */
    @Override
    public void execute(ApplicationData data, List<DeviceSpecification> deviceSpecs,
            ValidationManagerConfiguration valManagerConfig, ValidationResult results)
            throws PreflightingCheckerException
    {
        this.valManagerConfig = valManagerConfig;
        this.defaultLocale = checker.getDefaultLocale();

        // Check for keys with empty values - First the default localization and then the locales
        checkForEmptyValues(null, results);

        /*
         * Check for problems related to the non-default localization files
         */
        for (Locale l : resFolder.getAvailableLocales())
        {
            if (!l.equals(defaultLocale))
            {
                // Check for keys with empty values
                checkForEmptyValues(l, results);
            }
        }
    }

    /**
     * Auxiliary method to check for keys with empty values.
     * @param locale - The locale to be validated. If null, the method will validate the default localization resource
     * @param results 
     * @return A validation result
     * @throws PreflightingCheckerException 
     */
    private void checkForEmptyValues(Locale locale, ValidationResult results)
            throws PreflightingCheckerException
    {
        // Strings element to be validated. Can either be from the default localization resource or a locale one.
        StringsElement localeStringsElement;

        // Construct a list of missing keys
        List<String> keysWithEmptyValues = new ArrayList<String>();

        if (locale != null)
        {
            localeStringsElement = resFolder.getValuesElement(locale);
        }
        else
        {
            // Validate default localization resource
            localeStringsElement = stringsKeysDefault;
        }

        try
        {
            if (localeStringsElement != null)
            {
                // Find keys with empty values
                keysWithEmptyValues = findKeysWithMissingValues(localeStringsElement);

                ValidationResultData result;
                for (String key : keysWithEmptyValues)
                {
                    result = new ValidationResultData();
                    // Builders to construct the description and quickfix
                    String resultDescription;

                    // Create a result and return it
                    result.setSeverity(getSeverityLevel());

                    result.setConditionID(getId());

                    //Associate the result to the resFolder
                    result.addFileToIssueLines(resFolder.getFile(),
                            Collections.<Integer> emptyList());

                    // The result is different depending if we are validating the default localization files or not
                    if (locale != null)
                    {
                        String localeDisplayName = null;
                        if ((locale.getCountry() != null) && (locale.getCountry().length() > 0))
                        {
                            localeDisplayName = locale.getLanguage() + "_" + locale.getCountry(); //$NON-NLS-1$
                        }
                        else
                        {
                            localeDisplayName = locale.getLanguage();
                        }

                        // Construct description
                        resultDescription =
                                CheckerNLS
                                        .bind(CheckerNLS.LocalizationStringsChecker_localeStringEmptyValue,
                                                key, localeDisplayName);

                        result.setIssueDescription(resultDescription.toString());
                    }
                    else
                    {
                        //Set description 
                        result.setIssueDescription(CheckerNLS.bind(
                                CheckerNLS.LocalizationStringsChecker_defaultStringEmptyValue, key));
                    }

                    // Set quickfix  
                    result.setQuickFixSuggestion(CheckerNLS.LocalizationStringsChecker_stringEmptyValueQuickFix);
                    result.setInfoURL(ConditionUtils.getDescriptionLink(checker.getId(), getId(),
                            valManagerConfig));

                    // Add result to the result list
                    results.addValidationResult(result);
                }
            }

        }
        catch (Exception e)
        {
            String exceptionMessage;
            if (locale == null)
            {
                exceptionMessage =
                        CheckerNLS.LocalizationStringsChecker_Exception_EmptyValuesDefault;
            }
            else
            {
                exceptionMessage =
                        CheckerNLS.LocalizationStringsChecker_Exception_EmptyValuesLocale;
            }
            throw new PreflightingCheckerException(exceptionMessage, e);
        }
    }

    /**
     * Auxiliary method to look for empty values in a StringsElement
     * @param localeStringsElement - A strings element representing a localization resource.
     * @return A list containing keys with empty values.
     */
    private List<String> findKeysWithMissingValues(StringsElement localeStringsElement)
    {

        List<String> missingValues = new ArrayList<String>();

        if (localeStringsElement != null)
        {
            for (String key : localeStringsElement.getKeyList())
            {
                // Check value associated with the key
                if (localeStringsElement.getValue(key) != null)
                {
                    Object value = localeStringsElement.getValue(key);

                    // The value can either be a String or a List<String>.
                    if (value instanceof String)
                    {
                        if (((String) value).length() < 1)
                        {
                            // Empty value found!
                            missingValues.add(key);
                        }
                    }
                    else if (value instanceof List<?>)
                    {
                        if (((List<?>) value).size() < 1)
                        {
                            // Empty value found!
                            missingValues.add(key);
                        }
                    }
                }
                else
                {
                    missingValues.add(key);
                }

            }
        }

        return missingValues;
    }
}